【问题标题】:fscanf return value and linked listfscanf 返回值和链表
【发布时间】:2018-11-29 12:20:16
【问题描述】:

这是我的代码的一部分。

while(1)
    {
      struct client* newnode = malloc(sizeof(client));

      if(head->next != NULL)
      {
        newnode = newnode -> next;
      }

      if(head->next == NULL)
      {
       newnode->next = head->next;
       head->next=newnode;
      }


     ReadEOF = fscanf(fp1,"%d %s %s %s %s\n",&(newnode->ID),newnode->PW,newnode->NAME,newnode->ADDRESS,newnode->PNUM);

     if((ReadEOF)!= 5)
     {
       break;
     }

     ++NumofClient;
     printf("%d",NumofClient);

   }   //make newnodes

这些代码写在循环之前。

 struct client* head=malloc(sizeof(client));
 head->next = NULL;
 int NumofClient = 0;
 int ReadEOF;

这是结构客户端。

typedef struct client{
  int ID;
  char PW[100],NAME[100],ADDRESS[100],PNUM[100];
  struct client* next;
}client;

这是 client.txt 文件。

 123 aa aa aa aa aa
 234 bb bb bb bb bb
 567 cc cc cc cc cc

我预计 NumofClient 的值为 3。

但是当NumofClient的值为1时,我发现程序退出了循环。

这意味着 fscanf 函数的返回值在第二次尝试时不是 5。

或者,在链表实现过程中是否发生了错误?

如果你需要,我很乐意在评论中写出完整的代码

【问题讨论】:

    标签: c linked-list scanf


    【解决方案1】:

    您正在覆盖(内存泄漏)并将垃圾(非初始化值)分配给新节点:

      if(head->next != NULL)
      {
        newnode = newnode -> next;
      }
    

    我想你想要

      newnode->next = head;
      head = newnode;
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2015-06-09
      • 1970-01-01
      • 2019-05-04
      • 2015-09-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多