gpt4 book ai didi

c - 这段代码给了我一个段错误(核心转储)。我不太明白为什么?

转载 作者:行者123 更新时间:2023-11-30 15:29:55 25 4
gpt4 key购买 nike

#include <stdio.h>
#include <stdlib.h>

struct Node{ int Element; struct Node* Next;};

int main(){

struct Node *header=NULL;
struct Node *ptr;

在此处创建链接列表

ptr=header;
ptr->Next=NULL;
int x;
printf("Input the elements. End with zero.\n");
scanf("%d", &x);

int c=0;//Counter

读取每个元素

while(x!=0)
{
if(c==0)
{ header=(struct Node*)malloc(sizeof(struct Node));
ptr=header;
ptr->Element=x;
c++;
scanf("%d", &x);
}
else
{ ptr->Next=(struct Node*)malloc(sizeof(struct Node));
ptr=ptr->Next;
ptr->Element=x;
ptr->Next=NULL;
c++;
scanf("%d", &x);
}
}

printf("/n");

struct Node *temp;

if(header==NULL)
printf("List is empty.\n");
else
{
for(temp=header;temp!=NULL;temp=temp->Next)
{printf("%d\n", temp->Element);}
}

这里我正在打印列表。

}

另外,我真的根本不理解段错误。为什么它只是说“段错误:核心转储”而不是给我们更多详细信息?

最佳答案

您将 ptr 设置为 NULL:

ptr=header;

然后你尝试取消引用 NULL。此行将崩溃:

ptr->Next=NULL;

修正你的逻辑。

关于c - 这段代码给了我一个段错误(核心转储)。我不太明白为什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25956914/

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