我试图将节点插入单个链接列表。编译器在代码的遍历部分中产生的分割错误。
struct Node *start=NULL;
void traverse()
{
struct Node *t;
t=start;
if(t==NULL)
{
printf("Linked list is emptyn");
return;
}
printf("there are %d elements in linked list",count);
while (t != NULL)
{
printf(" %d ",t->data);
t=t->next;
}
printf(" %d ",t->data);
}
运行代码后:
Shaons-Air:VSC shaon$ cd "/Users/shaon/Desktop/VSC/" && gcc linkedlist.c -o linkedlist && "/Users/shaon/Desktop/VSC/"linkedlist
1.insert at the beginning2.insert at the end3.traverse
1
enter element
2
1.insert at the beginning2.insert at the end3.traverse
1
enter element
3
1.insert at the beginning2.insert at the end3.traverse
3
Segmentation fault: 11
,所以当t指向最后一个节点
t-> next = null然后你做
t = t->next;
//so t = null
所以当你做
时printf("%d",t-> data(;
它会创建SEG故障,因为T为空,并且没有任何数据零件
查看此代码:
while (t != NULL) // Keep repeating until t is NULL
{
printf(" %d ", t->data);
t=t->next;
}
printf(" %d ",t->data); // Now t is NULL but still you dereference it ...
^^^
dereference a NULL
因此,您继续使用t
为NULL
,然后进行t->data
!那是崩溃。
只需删除最后一个printf
,因为您已经打印了所有元素。