我花了几个小时试图找出这段代码出了什么问题。我尝试将代码放入 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
最佳答案
您必须将指向值的指针而不是值传递给 fscanf
(请注意 &temp->id
和 中的
;&
符号) >&temp->gpachar[]
-类型lname
和fname
自动衰减为指针):
while(fscanf(file1, "%s %s %d %f", temp->fname, temp->lname, &temp->id, &temp->gpa) != EOF) {
关于c - Fscanf 给出段错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42124341/