Hi im a beginner in C programming; i'm trying to learn list and pointers to a struct. Here its my program to implement a list element after element using pointers. Can somebody tell me why it gives me error segmentation fault core dumped?
#include<stdio.h>
#include<stdlib.h>
struct ListNode{
int x;
struct ListNode* nextPtr;
};
typedef struct ListNode ListNode;
typedef ListNode* ListNodePtr;
void insert(ListNodePtr* sPtr, int n);
int main()
{
int f;
scanf("%d", &f);
ListNodePtr startPtr=NULL;
while(f!=-1)
{
insert(&startPtr, f);
scanf("%d",&f);
printf("/n");
}
return 0;
}
void insert(ListNodePtr* sPtr, int n)
{
ListNodePtr newPtr;
newPtr=malloc(sizeof(ListNode));
if(newPtr!=NULL)
{
newPtr->x=n;
newPtr->nextPtr=NULL;
}
ListNodePtr q,w;
q=*sPtr;
w=q->nextPtr;
while(w!=NULL)
{
q=w;
w=q->nextPtr;
}
w=newPtr;
}
The first time through your insert:
q=*sPtr;
w=q->nextPtr;
*sPtr
equals NULL. You are dereferencing this which will cause a seg-fault on q->nextPtr;
.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.