C语言双向链表出现意外错误

3

我正在尝试根据节点数量n将元素插入我的双向链表。比如,如果n4,则输入的元素数量为:34 45 32 1,但出现了segmentation fault。有人可以告诉我问题出在哪里吗?

#include<stdio.h>
#include<malloc.h>

struct node{
            struct node *prev;
            struct node *next;
            int info;
            }*start;

create_list(int num)
{
 printf("Hi I entered!\n");
 struct node *q,*tmp;
 tmp= malloc(sizeof(struct node));
 tmp->info=num;
 tmp->next=NULL;

 if(start==NULL)
 {
  printf("Hi I am null!\n");
  tmp->prev=NULL;
  start->prev=tmp;
  start=tmp;
 }

 else
 {
  printf("Hi I am no more null!\n");
  q=start;
  while(q->next!=NULL)
  q=q->next;
  q->next=tmp;
  tmp->prev=q;
  }
}




int main(){

int choice, n, elem,i;
start = NULL;

 printf("Enter your choice of number: \n");
 scanf("%d", &choice);

 while(1)
      {

switch(choice)
{
  case 1:
     printf("Enter the number of nodes: \n");
     scanf("%d", &n);

     for(i=0; i<n; i++)
     {
       printf("Enter the elemnts: \n");
       scanf("%d", &elem);
       create_list(elem);
     }
     break;

 default:
         printf("You have tyoed wrong!\n");
     }

   }
 }
3个回答

3
if(start==NULL)
{
  ...
  start->prev=tmp;

如果start为空,那么上面的赋值是不正确的。我建议在分配新节点时将prev初始化为NULL,像这样:
tmp= malloc(sizeof(struct node));
tmp->info=num;
tmp->next=NULL;
tmp->prev=NULL;        // add this

if(start==NULL)
{
    printf("Hi I am null!\n");
    start=tmp;
}
....

3
你在这里试图取消引用一个空指针:
if(start==NULL)
{
    printf("Hi I am null!\n");
    tmp->prev=NULL;
    start->prev=tmp;    //start is NULL

由于指向结构体start的指针没有指向任何内存,因此您不能使用它来分配数据。


那么应该分配什么任务呢? - user227666
@user227666 你必须将 start 指向一个有效的内存块。start= malloc() 就是一个可行的方法。 - this

1
你有一个无限循环。在插入列表后设置一些变量。在switch case结束后检查该变量,并再次从while循环中退出。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接