c - Fscanf 给出段错误

标签 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;
};

文本文件中的一行示例:

约翰·多伊 1 3.6

约翰·史密斯 3 2.4

最佳答案

您必须将指向值的指针而不是值传递给 fscanf(请注意 &temp->id 中的 & 符号) >&temp->gpachar[]-类型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/

相关文章:

c - gdb 命令出错。 eclipse调试问题

c - Linux 上 fwrite 中的段错误

c - MikroC,绘制线图

c++ - char vector 可以越界吗?

c - ANSI C sscanf 给出段错误

c - 处理嵌入结构中的矩阵时出现段错误

c - 生产者消费者解决方案

c - 为什么 getchar 调用 printf 停止工作?

c++ - 成功调用析构函数或调用 empy 析构函数后出现段错误。 C++

c - 函数中的段错误