c语言我用尾插法读出来数据循环输出不了,求大佬帮看看

void Lend(void)
{
struct jieshu *head;
struct jieshu *str;
struct tushu *tushu=NULL;
int num;
int count=0;

head=create();
if(head==NULL)
{
printf("读取失败");
StudentMenu();
}

for(str=head;str!=NULL;str=str->next)
{
printf("%s %s %s %s %s",str->num,str->name,str->writer,str->press,str->kind);
}
}

struct jieshu *create(void) //创建借阅信息链表,返回链表头指针
{
struct jieshu *head;
struct jieshu *p1,*p2;

if((fp4=fopen("jieshu.txt","r"))==NULL)
{
printf("open jieshu.txt error!");
}

p1=p2=(struct jieshu *)malloc(sizeof(struct jieshu));
fscanf(fp4,"%s %s %s %s %s\n",p1->num,p1->name,p1->writer,p1->press,p1->kind);
while(!feof(fp4))
{
if(head==NULL)
{
head=p1;
}
else
{
p2->next=p1;
}
p2=p1;
p1=(struct jieshu *)malloc(sizeof(struct jieshu));
fscanf(fp4,"%s %s %s %s %s",p1->num,p1->name,p1->writer,p1->press,p1->kind);
}
p2->next = NULL;
free(p1);
free(p2);
fclose(fp4);
return head;
}

第1个回答  2020-07-09
在struct jieshu *create(void) 函数中
写代码时,创建指针的时候建议用NULL初始化指针例如struct jieshu *head=NULL;不然有可能会出错,例如if(head==NULL)有可能判断为假,
p2=p1;
free(p2);
你把最后的数据给free掉了
还有就是建议free掉对象后指针指向NULL.
相似回答