上天人 2022-10-15 20:47 采纳率: 66.7%
浏览 20
已结题

链表创建时发生的错误原因(C语言)

#include<stdio.h>
typedef struct node
{
int value;
struct node *b;
}
node;
node *makelist(int n);
void printlist(node *t);
int main()
{
int n=10;
printf("what's the lenth?");
scanf("%d",&n);
node *head=NULL;
head=makelist(n);
printlist(head);
return 0;
}
struct node *makelist(int n)
{
node *head=NULL;
node list[20];
for(int i=0;i<n-1;i++)
{
printf("what's the number:?");
scanf("%d",&(list[i].value));
list[i].b=&(list[i+1]);

}
 list[n-1].value=10;
 printf("%d",list[n-1].value);
 list[n-1].b=NULL;
 head=&(list[0]);
return head;

}
void printlist(struct node *t)
{
node *p=NULL;
p=t;
while(p->b!=NULL)
{
printf("%d ",p->value);
p=p->b;
}
printf("%d ",p->value);
}
输入1到9,输出的数大的离谱;
初学链表,这样做错哪了(清楚可用指针做,但不懂这种做法错因)

  • 写回答

2条回答 默认 最新

  • CSDN专家-link 2022-10-15 20:53
    关注

    node list[20];是函数内局部变量,函数结束后,数组内存就被释放了,你外面再使用这些地址,里面的值就不受控制了
    把node list[20]定义为全局变量

    typedef struct node
    {
        int value;
        struct node *b;
    }node;
    node list[20];
    //
    node *makelist(int n);
    void printlist(node *t);
    int main()
    {
        int n=10;
        printf("what's the lenth?");
        scanf("%d",&n);
        node *head=NULL;
        head=makelist(n);
        printlist(head);
        return 0;
    }
    struct node *makelist(int n)
    {
        node *head=NULL;
        for(int i=0;i<n;i++)
        {
            printf("what's the number:?");
            scanf("%d",&(list[i].value));
            if(i==n-1)
                list[i].b = NULL;
            else
                list[i].b=&(list[i+1]);
    
        }
        head=&(list[0]);
        return head;
    }
    void printlist(struct node *t)
    {
        node *p=NULL;
        p=t;
        while(p->b!=NULL)
        {
            printf("%d ",p->value);
            p=p->b;
        }
        printf("%d ",p->value);
    }
    
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论 编辑记录
查看更多回答(1条)

报告相同问题?

问题事件

  • 系统已结题 10月23日
  • 已采纳回答 10月15日
  • 创建了问题 10月15日

悬赏问题

  • ¥15 组策略中的计算机配置策略无法下发
  • ¥15 如何绘制动力学系统的相图
  • ¥15 对接wps接口实现获取元数据
  • ¥20 给自己本科IT专业毕业的妹m找个实习工作
  • ¥15 用友U8:向一个无法连接的网络尝试了一个套接字操作,如何解决?
  • ¥30 我的代码按理说完成了模型的搭建、训练、验证测试等工作(标签-网络|关键词-变化检测)
  • ¥50 mac mini外接显示器 画质字体模糊
  • ¥15 TLS1.2协议通信解密
  • ¥40 图书信息管理系统程序编写
  • ¥20 Qcustomplot缩小曲线形状问题