I am trying to append one list with another . If i pass a pointer-to-the-pointer of both the lists and just display them, then , the code works fine. But if i use code to reach the NULL pointer of the first list and then equate it to the first one of the second, then it gives a segmentation fault. Please let me know what the mistake is. Code is below :
#include<stdio.h>
#include<stdlib.h>
struct node
{
int data;
struct node* next;
}*Head,*New;
void display(struct node **p)
{
struct node *curptr;
curptr=*p;
if(curptr==NULL)
printf("list is empty");
else
{
while(curptr)
{
printf("->%d",curptr->data);
curptr=curptr->next;
}
}
}
void combine(struct node **a,struct node **b)
{
//display(&(*a));
struct node *aptr;
aptr=*a;
while(aptr)
aptr=aptr->next;
aptr->next=*b;
*b=NULL;
display(&(*a));
//display(&(*a));
//display(&(*b));
}
void main()
{
Head=NULL;
New=NULL;
int choice;
while(1)
{
case 9:
{
printf("Combining two lists");
combine(&Head,&New);
break;
}
The problem is here:
When you break out of the
whileloopaptrwill beNULLnext when you try to doaptr->nextyou get the SEGV.To fix this break out of the loop when you reach the last node(
aptr->nextwill beNULL) rather thanaptrbecomingNULL.Something on these line: