我想我已经在下面的代码中正确地实现了指针。但它会导致分段错误。有人可以解释为什么吗?
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;
}
}