PS *_*yak 0 c pointers linked-list list singly-linked-list
尝试使用Fedora gcc下面的代码,为一个简单的链接列表添加新节点到列表的尾部.编译时没有错误.在执行期间,它显示Segmentation Fault,Core Dumped.在MS Windows上,它正在运行.
#include<stdio.h>
#include<stdlib.h>
struct Node
{
int data;
struct Node *next;
};
void insertion(struct Node *);
void display(struct Node *);
int main(void)
{
struct Node *head;
head=NULL;
head->next=NULL;
int choice, cont;
do
{
printf("1.Insert 2.Display 3.Exit");
scanf("%d",&choice);
if(choice==1)
{
insertion(head);
}
else if(choice==2)
{
display(head);
}
else if(choice==3)
{
exit(0);
}
else
{
printf("Wrong choice");
}
printf("Continue? Press 1 otherwise 0:");
scanf("%d",&cont);
}while(cont==1);
return 0;
}
void insertion(struct Node *start)
{
int data;
struct Node *temp=NULL;
temp->next=NULL;
struct Node *mnew=NULL;
mnew->next=NULL;
mnew=(struct Node *)malloc(sizeof(struct Node));
printf("Enter data:");
scanf("%d",&data);
mnew->data=data;
if(start==NULL)
{
start=mnew;
}
else if(start!=NULL && start->next==NULL)
{
start->next=mnew;
}
else
{
temp=start;
while(temp->next!=NULL)
{
temp=temp->next;
}
temp->next=mnew;
}
}
void display(struct Node *start)
{
struct Node *temp=NULL;
temp->next=NULL;
if(start==NULL)
{
printf("\nNothing to display!");
}
else if(start!=NULL && start->next==NULL)
{
printf("%d",start->data);
}
else
{
temp=start;
while(temp!=NULL)
{
printf("%d",temp->data);
temp=temp->next;
}
}
}
Run Code Online (Sandbox Code Playgroud)
非常感谢您的帮助.
head=NULL;
head->next=NULL;
Run Code Online (Sandbox Code Playgroud)
这段代码永远不会工作,因为head如果它指向NULL(也称为无处),则无法访问或赋值属性.