如何正确传递包含结构体的指针数组?

问题描述 投票:0回答:0

我的代码没有任何疯狂的错误,但是当我尝试调试时它甚至无法启动。我相信这与 addBook 函数有关,我在该函数中尝试调用指针数组的元素。请让我知道我做错了什么以及传递包含结构的指针数组的正确方法。感谢您的任何帮助!我知道代码尚未完成,但其他所有内容都将基于此开始部分构建。

#include <stdio.h>              // Standard C input and output library
#include <stdlib.h>             // Standard C library
#include <time.h>               // Open the time library
#include <string.h>             // Standard String library
#include <ctype.h>              // c library
#define _CRT_SECURE_NO_WARNINGS         
#define FLUSH myFlush() 

typedef struct {
    char title[50];
char author[50];
int numberOfBooks;
} LIBRARY;

void addBook();  //completely new to the library
int getSize();
void myFlush();

int main() {
int size = getSize();
int eSize = 0;
LIBRARY** library = calloc(size, sizeof(LIBRARY*));
}

int getSize() {
int size;
printf("\nHow many books are in this library?");
scanf("%i", &size); FLUSH;
printf("\n\n");
return size;
}

void addBook(int size, int* eSize, LIBRARY** library) {
library[*eSize] = calloc(1, sizeof(LIBRARY));
printf("\nPlease add the title of the next book to be added to the library\n:");
scanf("%s", library[*eSize]->title); FLUSH;
printf("\nPlease add the author of %s\n:", library[*eSize]->title);
scanf("%s", library[*eSize]->author); FLUSH;
printf("\nPlease input how many copies of %s you wish to add\n:", library[*eSize]->title);
scanf("%i", &library[*eSize]->numberOfBooks); FLUSH;
*eSize = *eSize + 1;
}

void myFlush() {
while (getchar() != '\n');
}// end myFlush

我尝试在 main 中使用 LIBRARY* library = calloc(size, sizeof(library)) ,但是当我尝试 calloc addBook 函数中的每个元素时,它会给出错误。所以我想也许我会把 LIBRARY library[*eSize] = calloc(1, sizeof(library)) 放在 addBook 函数中,但它说 *eSize 必须是一个常量。所以我现在真的不知道该怎么办。

dynamic-memory-allocation array-pointer
© www.soinside.com 2019 - 2024. All rights reserved.