gpt4 book ai didi

创建循环链接列表编译器停止工作

转载 作者:行者123 更新时间:2023-11-30 20:51:19 25 4
gpt4 key购买 nike

编译器停止工作,请给我一些解决方案

#include<stdio.h>
#include<stdlib.h>
typedef struct
{
int data;
struct node *next;
}node;
node * create()
{
node *p;
p=malloc(sizeof(node));
p->next=NULL;
return p;
}
void add(node **h,int ele)
{ node *temp;
temp=(*h);
node *p=create();
while(temp->next!=temp)
temp=temp->next;
temp->next=p;
p->next=temp;
p->data=ele;
(*h)=temp;

}


void main()
{ int ch,ele;
node *h;
h->next=h;

do
{ printf("\n1 add 2 delete 3 insert at kth position 4 delete at kth position");
scanf("%d",&ch);

if(ch==1)
{
scanf("%d",&ele);
add(&h,ele);
}
//if(ch==2)

}while(ch!=5);

}

最佳答案

就像我在评论中所说的那样,我的猜测是您发生了崩溃,当您运行程序时程序会停止,并且它的构建没有错误。

原因是您使用了本地非静态变量h而没有对其进行初始化。除非初始化,否则所有局部非静态变量都具有不确定值,并且在未初始化的情况下使用这些变量会导致未定义的行为

解决方案非常简单:为节点分配内存(作为普通变量或动态分配)并用它初始化指针 h

大多数编译器实际上能够检测此类问题,但由于它在语法和语义上都是合法的,因此不会发出错误,而是发出警告。如果您没有收到此类警告,那么您需要启用更多警告。

关于创建循环链接列表编译器停止工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33124767/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com