[英]Segmentation fault while implementing linked list in C
I'm trying to create a simple linked list and insert a node at the end of the list. 我正在尝试创建一个简单的链接列表,并在列表末尾插入一个节点。 I'm getting a segmentation fault.
我遇到了细分错误。
#include <stdio.h>
#include <stdlib.h>
struct node{
int data;
struct node *link;
};
void create(struct node *head){
struct node* second = NULL;
struct node* last = NULL;
second = (struct node*)malloc(sizeof(struct node));
last = (struct node*)malloc(sizeof(struct node));
second -> data = 2;
last -> data = 3;
head -> link = second;
second -> link = last;
last -> link = NULL;
}
void insert_ending(struct node *head){
struct node* temp = NULL;
struct node* temp1 = NULL;
temp1 = (struct node*)malloc(sizeof(struct node));
temp1 -> data = 5;
temp1 -> link = NULL;
temp = head;
while(temp != NULL){
temp = temp -> link;
}temp -> link = temp1;
}
void PrintList(struct node *head){
while( head != NULL ){
printf(" %d -->", head -> data);
head = head -> link;
}
printf("\n");
}
int main(){
struct node* head = NULL;
head = (struct node*)malloc(sizeof(struct node));
head -> data = 1;
head -> link = NULL;
create(head);
PrintList(head);
insert_ending(head);
PrintList(head);
return 0;
}
I'm getting a segmentation fault. 我遇到了细分错误。 The output is as follows.
输出如下。
1 --> 2 --> 3 --> Segmentation fault (core dumped)
1-> 2-> 3->分段错误(核心已转储)
in your insert function you need to change to : 在插入函数中,您需要更改为:
temp = head;
while(temp -> link != NULL){
temp = temp -> link;
}
temp -> link = temp1;
the reason is that when you loop with while until temp == null, you can't afterward do: temp -> link because temp is allready null. 原因是,当您使用while循环直到temp == null时,您之后不能再执行:temp-> link,因为temp都已为null。
In the function 'insert_ending' in the while loop you want to change the condition from: 在while循环中的函数“ insert_ending”中,您希望将条件更改为:
while ( temp != NULL )
to: 至:
while ( temp->link != NULL )
because now once the loop is finished, temp is NULL and then you try to dereference it (a NULL pointer) and get an error. 因为现在循环完成后,temp为NULL,然后尝试取消引用它(一个NULL指针)并得到一个错误。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.