我传入 argv[1] 作为文件名,但出现段错误,但我不知道为什么。我正在使用一个链表来保存包含 2 个字符和一个 int 的 car 结构的实例。我觉得问题出在我的 fscanf 语句中,但我不确定。
void readFile(List *north, List *east, List *south, List *west, char *fileName) {
char *file = fileName;
FILE *fp = fopen(file, "r");
if(!fp) {
printf("File could not be opened...");
return;
}
while(!feof(fp)) {
Car *temp = NULL; //Initialize a blank car
fscanf(fp, "%s %s %d", &temp->direc, &temp->turn, &temp->time); //scan the direction path and time
//into the Car Node
//Add to North List
if(temp->direc == 'N') {
insertBack(north, temp);
}
//Add to East List
if(temp->direc == 'E') {
insertBack(east, temp);
}
//Add to South List
if(temp->direc == 'S') {
insertBack(south, temp);
}
//Add to West List
if(temp->direc == 'W') {
insertBack(west, temp);
}
else {
printf("Something went wrong...");
return;
}
}
fclose(fp);
}
最佳答案
Car *temp = NULL; //Initialize a blank car
您不是在此处初始化“空白”汽车。 temp
变量只是NULL
。在执行 fscanf
之前使用 malloc
分配空间:
汽车 *temp = malloc(sizeof(Car));
如果“空白”意味着将分配的空间清零,请使用calloc
。
关于c - 尝试读取文件时出现段错误?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47362780/