【问题标题】:Fscanf giving a segmentation faultFscanf 给出分段错误
【发布时间】: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


【解决方案1】:

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

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

【讨论】:

  • 不敢相信我错过了。谢谢!我习惯了java并且一直忘记语法。允许我接受答案。
  • 澄清一下,char数组的名字大致相当于保存char数组首地址的变量;但整数或浮点数的名称大致相当于整数或浮点数的值。这意味着您必须明确指出整数或浮点名称的地址,而您可以使用不带“address of”运算符的数组的简写名称。
  • @EdwinBuck 明白了!一直忘记做这个,太习惯java了!
猜你喜欢
  • 2017-03-29
  • 2015-02-09
  • 2020-03-24
  • 1970-01-01
  • 1970-01-01
  • 2011-05-25
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多