我试图通过访问指针并从其他函数分配内存来写入指针。但是在 while 语句的几次迭代之后,核心转储被抛出。我从确保格式正确的文件中获取数据。
当仍有要从文件中读取的名称时失败(使用调试器检查)
主要的
Category *category = NULL;
memoryAllocate(&category);
内存分配
memoryAllocate(Category **category){
int elements;
char name[NAME];
int i = 0;
FILE *fPeces;
[...]
//Get the number of elements from the file
fscanf(fPeces, "%d", &elements);
*category = (Category *)malloc(sizeof(Category) * elements));
if(*category == NULL){
//ERROR
}
else{
while(i < elements){
fgets(name, NAME, fPeces);
strcpy(category[i]->categoryName, name);
i++;
}
}
结构
typedef struct categoria {
char categoryName[NAME];
int part_num;
Parts *parts;
} Category;
FILE(第一个数字是类别数,其余是名称)
6
category 1
category 2
category 3
category 4
category 5
category 6