//目标:将文件中的数据加载到结构中
typedef struct {
int year;
char* make;
char* model;
int miles;
} Car;
void fill_garage(Car** garage, char* cars, int* size);
int main(int argc, char** argv)
{
if(argc<3)
{
printf("Not enough arguments.n");
return 0;
}
int size;
Car** garage;
fill_garage(garage, argv[1], &size);
return 0;
}
void fill_garage(Car** garage, char* cars, int* size)
{
int i;
FILE* inputF=fopen(cars, "r");
fscanf(inputF, "%d", size);
garage=malloc(sizeof(Car)*(*size));
for(i=0; i<(*size); i++)
{
garage[i].make=malloc(sizeof(char)*MAX_STRING_LEN);
garage[i].model=malloc(sizeof(char)*MAX_STRING_LEN);
//The line below causes a segmentation fault when there are no errors
fscanf(inputF, "%d %s %s %d", &garage[i].year, garage[i].make, garage[i].model, &garage[i].miles);
}
}
//我不希望任何人只给我更正的代码(尽管那会很好)如果你能指出一个资源,我可以在那里学习指针,那就太好了。如果你想看的话,这是作业单。http://pastebin.com/LNeCx70m
-
你必须将
garage
的地址传递给fill_garage()
,所以这个Car** garage; fill_garage(garage, argv[1], &size);
应该是
Car *garage; fill_garage(&garage, argv[1], &size); /* ^ pass the address of garage */
-
固定大小的字符串不需要
malloc()
,只需像一样重新定义结构即可typedef struct { int year; char make[MAX_STRING_LEN]; char model[MAX_STRING_LEN]; int miles; } Car;
-
检查
fopen()
和malloc()
的返回值,如果它们都失败,则返回NULL
,如果未能打开文件,则会导致未定义的行为。同时检查fscanf()
的返回值。 -
对于
printf()
包括stdio.h
,对于malloc()
包括fscanf()
和stdlib.h
。
我修复了你的代码,所以原则上不会有任何问题
#include <stdio.h>
#include <stdlib.h>
#define MAX_STRING_LEN 128
typedef struct {
int year;
char make[MAX_STRING_LEN];
char model[MAX_STRING_LEN];
int miles;
} Car;
void fill_garage(Car **garage, char *cars, int *size);
int main(int argc, char** argv)
{
if (argc < 3)
{
printf("Not enough arguments.n");
return 0;
}
int size;
Car *garage;
fill_garage(&garage, argv[1], &size);
return 0;
}
void fill_garage(Car **output, char *cars, int *size)
{
int i;
FILE *inputF;
Car *garage;
if (output == NULL)
return;
*output = NULL;
inputF = fopen(cars, "r");
if (inputF == NULL)
return;
if (fscanf(inputF, "%d", size) != 1)
{
fclose(inputF);
return;
}
garage = malloc(sizeof(*garage) * *size);
*output = garage;
if (garage == NULL)
{
fclose(inputF);
return;
}
i = 0;
while ((i < *size) && (fscanf(inputF, "%d%127s%127s%d", &garage[i].year, garage[i].make,
garage[i].model, &garage[i].miles) == 4))
{
i += 1;
}
}