I started learning C programming a few days ago through the book, Programming in C, and I have prior knowledge of java. Inserting a node into a linked list is very easy in java, but I thought if I could do the same in C. So, I came up with this program,
#include "node.h"
void insertEntry(struct node* root, struct node* after)
{
struct node* first = root;
while(first != (struct node*) 0)
{
if(first->value == after->value)
{
struct node ins;
ins.value = 3456;
ins.next = first->next;
first->next = &ins;
}
first = first->next;
}
}
int main(void)
{
struct node n1, n2, n3;
struct node* list_pointer = &n1;
n1.value = 100;
n1.next = &n2;
n2.value = 200;
n2.next = &n3;
n3.value = 300;
n3.next = (struct node*) 0;
void insertEntry(struct node* root, struct node* after);
while (list_pointer != (struct node*) 0)
{
printf("%i\n", list_pointer->value);
list_pointer = list_pointer->next;
}
printf("\n");
list_pointer = &n1;
insertEntry(list_pointer, &n2);
while (list_pointer != (struct node*) 0)
{
printf("%i\n", list_pointer->value);
list_pointer = list_pointer->next;
}
return 0;
}
node.h
#include <stdio.h>
struct node
{
int value;
struct node* next;
};
Basically, this program takes pointer to the first element of the linked list and the pointer to the element after which it is to be inserted, and inserts a new node after this node.
But when I run this, my program crashes and I cannot find where or why this error occurs. I looked over to the code in java and tried to implement the same in C.
Thank you.
gdbto find exactly where the segmentation fault occurs?