【发布时间】:2021-03-17 07:28:17
【问题描述】:
我在 C 中实现了一个链表。
问题是,每当我尝试使用函数print_list(struct linked_list *list) 打印节点数据时,都会出现分段错误。
我不确定是什么原因造成的,因为当我尝试print(struct linked_list *list) 时,它工作正常。
而且,当我尝试动态分配内存时,它也可以正常工作。但我很好奇这样的代码有什么问题?为什么使用print 不会导致同样的错误?
#include <stdio.h>
#include <stdlib.h>
struct node{
char data;
struct node* next;
};
struct linked_list{
struct node *head;
};
void concat(struct linked_list* list1, struct linked_list* list2)
{
struct node* tmp = list1->head;
while(tmp->next != NULL)
tmp = tmp->next;
tmp->next = list2->head;
}
void print_list(struct linked_list *list)
{
struct node* tmp = list->head;
while(tmp != NULL){
printf("%c - ", tmp->data);
tmp = tmp->next;}
printf("\n");
}
void print(struct linked_list *list)
{
struct node* tmp = list->head;
printf("%c\n", tmp->data);
tmp = tmp->next;
printf("%c\n", tmp->data);
tmp = tmp->next;
printf("%c\n", tmp->data);
}
int main()
{
struct linked_list list1,list2;
struct node n1,n2,n3,n4,n5;
n1.data = 'A';
n2.data = 'B';
n3.data = 'C';
n4.data = 'D';
n5.data = 'E';
n1.next = &n2;
n2.next = &n3;
n4.next = &n5;
list1.head = &n1;
list2.head = &n4;
printf("List 1 containes :\n");
print_list(&list1);
concat(&list1,&list2);
printf("List 1 after concat: \n" );
print_list(&list1);
return 0;
}
【问题讨论】:
-
我的猜测是列表中的最后一个节点没有
NULLasnext链接。您将节点创建为本地数据而不初始化它们,这在 C 中意味着它们具有“垃圾”值。说struct node n1 = {'a'};应该可以。next字段被隐式初始化为空指针。 -
我在here 中复制粘贴相同的内容,我没有看到任何段错误。
标签: c struct linked-list segmentation-fault