问题
I am trying to insert elements in my double linked list based on the number of nodes n. Like if n is 4 then number of elements entered are: 34 45 32 1 but getting segmentation fault. Can anybody tell me where I am going wrong?
#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");
}
}
}
回答1:
if(start==NULL)
{
...
start->prev=tmp;
If start is NULL, then the assignment above is incorrect.
I would suggest initializing prev to NULL when you allocate the new node like this:
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;
}
....
回答2:
You are trying to dereference a NULL pointer here:
if(start==NULL)
{
printf("Hi I am null!\n");
tmp->prev=NULL;
start->prev=tmp; //start is NULL
Since pointer to struct start does not point to any memory, you can't use it to asing data.
回答3:
You have an infinite while loop. Set some variable after you have finished inserting into the list. check this variable after coming out of the switch case and break again from the while loop.
来源:https://stackoverflow.com/questions/18763139/unexpected-error-in-double-linked-list-in-c