这是我的代码的一部分。
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。
或者,是不是链表执行过程中出现了错误?
如果你需要,我很乐意在评论中写下完整的代码
最佳答案
您正在覆盖(内存泄漏)并将垃圾(非初始化值)分配给新节点:
if(head->next != NULL)
{
newnode = newnode -> next;
}
我觉得你想要
newnode->next = head;
head = newnode;
关于c - fscanf返回值和链表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53538944/