在C中实现链表时出现分段错误
Segmentation fault while implementing linked list in C
我正在尝试创建一个简单的链表并在链表的末尾插入一个节点。我遇到了分段错误。
#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;
}
我遇到了分段错误。输出结果如下。
1 --> 2 --> 3 -->
Segmentation fault (core dumped)
在您的插入函数中,您需要更改为:
temp = head;
while(temp -> link != NULL){
temp = temp -> link;
}
temp -> link = temp1;
原因是当你用 while 循环直到 temp == null 时,你不能之后做:temp -> link 因为 temp 已经是 null。
在函数 'insert_ending' 的 while 循环中你想改变
条件来自:
while ( temp != NULL )
致:
while ( temp->link != NULL )
因为一旦循环结束,temp 为 NULL,然后您尝试取消引用它(一个 NULL 指针)并得到一个错误。
我正在尝试创建一个简单的链表并在链表的末尾插入一个节点。我遇到了分段错误。
#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;
}
我遇到了分段错误。输出结果如下。
1 --> 2 --> 3 --> Segmentation fault (core dumped)
在您的插入函数中,您需要更改为:
temp = head;
while(temp -> link != NULL){
temp = temp -> link;
}
temp -> link = temp1;
原因是当你用 while 循环直到 temp == null 时,你不能之后做:temp -> link 因为 temp 已经是 null。
在函数 'insert_ending' 的 while 循环中你想改变 条件来自:
while ( temp != NULL )
致:
while ( temp->link != NULL )
因为一旦循环结束,temp 为 NULL,然后您尝试取消引用它(一个 NULL 指针)并得到一个错误。