0

这个程序是创建一个链接列表。当我运行这个程序时,它给了我一个分段错误。

#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
4

1 回答 1

3

在它的初始声明和初始化之后,你永远不会分配任何东西root,所以它总是NULL,然后你继续在travel().

struct node *t1;
t1=root;

// what if root is NULL?  Too late... segfault (you hope)
while( t1->next!=NULL)
于 2012-05-07T19:04:05.617 回答