为什么在我第一次在我的代码中插入一个项目后我的代码中出现分段错误
Why is a segmentation fault occuring in my code after the first time i insert an item in my code
/*Linked list insertin deletion display
我声明了一个struct node *head=NULL的全局变量;
linkedlistlinkedlistlinkedlisr=tlinkedlistlinkedlistlinkedlist
linkedlistlinkedlistlinkedlisr=tlinkedlistlinkedlistlinkedlist
void insert(int x)//i guess the problem might be that temp is pointing to head as well as new
{
struct node *temp=NULL;
struct node *new;
new=(struct node*)malloc(sizeof(struct node));
new->data=x;
new->next=NULL;
if(head==NULL)
{
head=new;
temp=head;
}
else
{
temp->next=new;
temp=new;
}
}
temp->next=new
很可能是您的问题。在函数的顶部,您将 temp 设置为 NULL 并使用 ->
运算符,您将取消引用空指针。
head==NULL
情况下的代码是可以的。但在 else
的情况下,您需要正确插入节点。
下面的代码将在列表末尾插入节点。
void insert(int x)
{
struct node *temp=NULL;
struct node *newnode;
newnode= malloc(sizeof(struct node));
newnode->data=x;
newnode->next=NULL;
if(head==NULL)
{
head=newnode;
}
else
{
temp = head;
while (temp->next != NULL)
temp = temp->next;
temp->next=newnode;
}
}
如果要在列表的开头插入,则需要修改else
条件,如图所示。
else
{
newnode->next=head;
head = newnode;
}
此外,还有以下提示
- 避免使用
new
,因为它是 C++ 中的关键字
- 不转换
malloc
的结果
/*Linked list insertin deletion display
我声明了一个struct node *head=NULL的全局变量;
linkedlistlinkedlistlinkedlisr=tlinkedlistlinkedlistlinkedlist
linkedlistlinkedlistlinkedlisr=tlinkedlistlinkedlistlinkedlist
void insert(int x)//i guess the problem might be that temp is pointing to head as well as new
{
struct node *temp=NULL;
struct node *new;
new=(struct node*)malloc(sizeof(struct node));
new->data=x;
new->next=NULL;
if(head==NULL)
{
head=new;
temp=head;
}
else
{
temp->next=new;
temp=new;
}
}
temp->next=new
很可能是您的问题。在函数的顶部,您将 temp 设置为 NULL 并使用 ->
运算符,您将取消引用空指针。
head==NULL
情况下的代码是可以的。但在 else
的情况下,您需要正确插入节点。
下面的代码将在列表末尾插入节点。
void insert(int x)
{
struct node *temp=NULL;
struct node *newnode;
newnode= malloc(sizeof(struct node));
newnode->data=x;
newnode->next=NULL;
if(head==NULL)
{
head=newnode;
}
else
{
temp = head;
while (temp->next != NULL)
temp = temp->next;
temp->next=newnode;
}
}
如果要在列表的开头插入,则需要修改else
条件,如图所示。
else
{
newnode->next=head;
head = newnode;
}
此外,还有以下提示
- 避免使用
new
,因为它是 C++ 中的关键字 - 不转换
malloc
的结果