该程序用于创建链接列表。 当我运行这个程序时,它会给我一个分段错误。
#include <stdio.h>
#include <stdlib.h>
struct node {
int data;
struct node *next, *prev;
};
struct node *root=NULL;
void push (int);
void pop (void );
struct node * create_node (int );
void travel (void );
int main()
{
int i, j, choice, count;
printf("enter choice\n");
scanf("%d", &choice);
count = 0;
while (choice == 1) {
printf("enter a data element");
scanf("%d", &j);
count++;
printf("enter choice\n");
scanf("%d", &choice);
}
printf("the link list is \n");
//travel function to be created
travel();
}
void push(int data)
{
struct node *t1;
t1=root;
while( t1->next!=NULL)
{
t1=t1->next;
}
t1->next=create_node( data);
}
void pop()
{
}
void travel (void )
{
struct node *t1;
t1=root;
while (t1->next!=NULL)
{
printf("%d ",t1->data);
}
printf("%d ",t1->data);
}
struct node * create_node (int data)
{
struct node *p = (struct node *) malloc (sizeof(struct node));
p->data=data;
p->next=NULL;
p->prev=NULL;
return p;
}
可能是什么错误? 这就是我执行的方式
user@ubuntu:~/programming$ ./a.out
enter choice
1
enter a data element45
enter choice
1
enter a data element67
enter choice
1
enter a data element89
enter choice
0
the link list is
Segmentation fault
答案 0 :(得分:3)
在初始声明和初始化之后,您永远不会为root
分配任何内容,因此它始终为NULL
,您可以在travel()
中取消引用它。
struct node *t1;
t1=root;
// what if root is NULL? Too late... segfault (you hope)
while( t1->next!=NULL)