I'm creating a linked list with some insert functions.
This method work fine :
void insert_before(){
struct node *new_node, *ptr, *preptr;
int pivot;
new_node = (struct node*)malloc(sizeof(struct node));
ptr = link;
preptr = link;
printf("\n Enter the data : ");
scanf("%d", &new_node->data);
printf("\n Enter the value before which the data has to be inserted : ");
scanf("%d", &pivot);
while(ptr->data != pivot){
preptr = ptr;
ptr = ptr->next;
}
preptr->next = new_node;
new_node->next = ptr;
}
However, I got Cannot access memory at address 0x8
in this method :
void insert_after(){
struct node *new_node, *ptr, *preptr;
int pivot;
new_node = (struct node*)malloc(sizeof(struct node));
ptr = link;
preptr = link;
printf("\n Enter the data : ");
scanf("%d", &new_node->data);
printf("\n Enter the value after which the data has to be inserted : ");
scanf("%d", &pivot);
while(preptr->data != pivot){
preptr = ptr;
ptr = ptr->next;
}
preptr->next = new_node;
new_node->next = ptr;
}
Note that both of the method use the same struct* link
, and the only difference is on the looping while(preptr->data != pivot)
.
Why does the first code working fine, but the second one broken?
Thanks for your help
PS : This is my whole project (very short), in case you need it : https://pastebin.com/wsMEicGv