【发布时间】:2017-02-08 21:52:09
【问题描述】:
我花了几个小时试图找出这段代码出了什么问题。我尝试使用将代码放在 feof while 循环中,以及将 fscanf 从循环中取出,以便它只运行一次。即使文件中的数据是有效的,这些更改仍然会引发分段错误。
struct student *temp = (ident*) malloc (sizeof(ident));
while(fscanf(file1, "%s %s %d %f", temp->fname, temp->lname, temp->id, temp->gpa) != EOF) {
if(head == NULL)
head = temp;
else {
struct student *traverse = head;
while(traverse->next != NULL)
traverse = traverse->next;
traverse->next = temp;
printf("added");
}
}
以下是结构体:
struct student{
char fname[256];
char lname[256];
unsigned int id;
float gpa;
struct student *next;
};
文本文件中的一行示例:
约翰·多伊 1 3.6
约翰·史密斯 3 2.4
【问题讨论】:
-
缺少两个 & 符号
-
@wilfplasser 谢谢!
-
the code in a feof while loop不要那样做。见:stackoverflow.com/q/5431941/905902 -
@wildplasser 感谢您的提醒!会坚持使用 fscanf,只是使用 feof 来尝试找出问题所在。
标签: c segmentation-fault