Fscanf给出了分段错误

时间:2017-02-08 21:52:09

标签: c segmentation-fault

我花了几个小时试图弄清楚这段代码出了什么问题。我尝试过将代码置于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;
};

文本文件中的一行示例:

john doe 1 3.6

约翰史密斯3 2.4

1 个答案:

答案 0 :(得分:0)

您必须将指针传递给值而不是值fscanf(注意& - &temp->id&temp->gpa中的符号; char[] - 类型lnamefname自动衰减为指针):

while(fscanf(file1, "%s %s %d %f", temp->fname, temp->lname, &temp->id, &temp->gpa) != EOF) {