| 网站首页 | 业界新闻 | 小组 | 威客 | 人才 | 下载频道 | 博客 | 代码贴 | 在线编程 | 编程论坛
欢迎加入我们,一同切磋技术
用户名:   
 
密 码:  
共有 977 人关注过本帖
标题:动态链表建立与输出错误
只看楼主 加入收藏
hcs_xiaohan
Rank: 2
等 级:论坛游民
帖 子:40
专家分:23
注 册:2016-7-4
结帖率:91.67%
收藏
已结贴  问题点数:20 回复次数:4 
动态链表建立与输出错误
建立动态链表,存储学生的学号和成绩并输出。

代码如下:

#include<stdio.h>
#include<malloc.h>
struct student
{
    long num;
    float score;
    struct student *next;
};
struct student *creat()
{
    struct student *head,*p,*pb;
    head=NULL;
    p=pb=(struct student *)malloc(sizeof(struct student));
    scanf("%ld,%f",&p->num,&p->score);
    p->next=NULL;
    while(p->num!=-1)
    {
        if(head==NULL)
            head=p;
        else
            pb->next=p;
        pb=p;
        p=(struct student *)malloc(sizeof(struct student));
        scanf("%ld,%f",&p->num,&p->score);
    }
    p->next=NULL;
    return head;
}
void print(struct student *head)
{
    struct student *pp;
    pp=head;
    while(pp!=NULL)
    {
        printf("%ld%5.1f\n",pp->num,pp->score);
        pp=pp->next;
    }
}
void main()
{
    struct student *creat();
    void print(struct student *head);
    struct student *head;
    head=creat();
    print(head);
}


运行时输入一组数据没问题,但输入两组以上就会发生如下错误:
图片附件: 游客没有浏览图片的权限,请 登录注册


请各位为我指点指点。
搜索更多相关主题的帖子: include 动态 
2016-09-21 20:27
linlulu001
Rank: 13Rank: 13Rank: 13Rank: 13
等 级:贵宾
威 望:20
帖 子:944
专家分:4047
注 册:2016-4-13
收藏
得分:20 

struct student *creat()
{
    free(p);            //最后一个-1的结点是没用的,既然没用就释放掉
    pb->next=NULL;     //p->next=NULL这个p不在这个链表内,实际上链表的尾结点的指针还是野指针。
    return head;
}
void print(struct student *head)
{
  
    {
        printf("%ld%5.1f\n",pp->num,pp->score);
        pp=pp->next;
        free(head);                        //链表用完最好养成释放它的习惯
        head=pp;
    }
}
2016-09-22 10:44
hcs_xiaohan
Rank: 2
等 级:论坛游民
帖 子:40
专家分:23
注 册:2016-7-4
收藏
得分:0 
回复 2楼 linlulu001
释放节点好像也没有解决报错问题啊?
2016-09-22 19:35
linlulu001
Rank: 13Rank: 13Rank: 13Rank: 13
等 级:贵宾
威 望:20
帖 子:944
专家分:4047
注 册:2016-4-13
收藏
得分:0 
释放结点不是为了解决报错问题,释放结点是一个良好的习惯。
struct student *creat()里的p->next=NULL;改成pb->next=NULL; 我在上面不都指出来了吗。

[此贴子已经被作者于2016-9-22 20:16编辑过]

2016-09-22 20:11
hcs_xiaohan
Rank: 2
等 级:论坛游民
帖 子:40
专家分:23
注 册:2016-7-4
收藏
得分:0 
回复 4楼 linlulu001
抱歉,我看错了,的确是那儿的问题。多谢你咯!
2016-09-22 20:39
快速回复:动态链表建立与输出错误
数据加载中...
 
   



关于我们 | 广告合作 | 编程中国 | 清除Cookies | TOP | 手机版

编程中国 版权所有,并保留所有权利。
Powered by Discuz, Processed in 0.019614 second(s), 10 queries.
Copyright©2004-2024, BCCN.NET, All Rights Reserved