Reputation: 3297
I think I have implemented the pointer correctly in below code. But it causes Segmentation fault. Can someone explain why?
struct list
{
int index;
struct list *next;
};
void add(struct list *l,int index)
{
struct list *temp=l;
if(l==NULL)
{
temp=(struct list *)malloc(sizeof(struct list));
temp->index=index;
temp->next=NULL;
l=temp;
}
else
{
while(temp->next!=NULL)
temp=temp->next;
struct list *nnode=(struct list *)malloc(sizeof(struct list));
nnode->index=index;
nnode->next=NULL;
temp->next=nnode;
}
}
main()
{
struct list *l;
l=NULL;
int el;
scanf("%d",&el);
add(l,el);
while(l->next!=NULL) //It causes seg fault
{
printf(" %d ",l->index);
l=l->next;
}
}
Upvotes: 0
Views: 85
Reputation: 36082
This code doesn't do what you think it does:
void add(struct list *l,int index)
{
struct list *temp=l;
if(l==NULL)
{
temp=(struct list *)malloc(sizeof(struct list));
temp->index=index;
temp->next=NULL;
l=temp;
}
...
the parameter l will not change since you are just passing it as a pointer, in order to change what l points to you need to pass the address of l
void add(struct list **l,int index)
{
struct list *temp;
if(*l==NULL)
{
temp=(struct list *)malloc(sizeof(struct list));
temp->index=index;
temp->next=NULL;
*l=temp;
}
...
otherwise the change will not reach outside the function scope.
Upvotes: 3
Reputation: 17312
This code shouldn't segfault if you just call add once, but I assume you call other functions and pass the list which is still NULL
you should send a pointer to pointer to the list instead
void add(struct list **l,int index)
{
if(*l==NULL) {
*l=(struct list *) malloc(sizeof(struct list));
}
}
Otherwise it will still be NULL
when add returns, because you only initialize a copy of the pointer, or if this confuses you could just initialize the list in main()
and avoid initialization in add()
Upvotes: 2