我花了几个小时试图弄清楚这段代码出了什么问题。我尝试过将代码放入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->gpa符号; char[]类型的lnamefname自动衰减为指针) :

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/

10-11 22:46
查看更多