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


#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("%dn", temp->Element);}
}

在这里,我正在打印列表。

}

另外,我真的完全不了解分段错误。为什么它只说"分段错误:核心转储"而不是给我们更多细节?

将 ptr 设置为 NULL:

ptr=header;

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

ptr->Next=NULL;

修正你的逻辑。

最新更新