Hii , i Was implementing a trie in C ... but i am getting an error in the insert_trie function .
I could not figure out why the root node is not getting updated . Please help me with this.
#include<stdio.h>
#include<stdlib.h>
#include<malloc.h>
typedef struct
{
char value;
int level;
struct node *next;
struct node *list;
}node;
node *trie = NULL;
node *init_trie()
{
node *new = (node *)malloc(sizeof(node));
if(trie == NULL)
{
new->value = '$';
new->next = NULL;
new->list = NULL;
new->level = 0;
trie = new;
printf("\n Finished initializing the trie with the value %c",trie->value);
return trie;
}
printf("\n Trie is already initialized");
return trie;
}
node *insert_trie(char *s)
{
node *nodepointer = trie;
node *new = (node *)malloc(sizeof(node));
node *save = NULL;
int i=0;
while(s[i]!=NULL)
{
nodepointer = nodepointer->list;
while(nodepointer!=NULL)
{
if(s[i] == nodepointer->value)
{
printf("\n Found %c",nodepointer->value);
nodepointer = nodepointer->list;
i++;
}
save = nodepointer;
nodepointer = nodepointer->next;
}
new->value = s[i];
new->next = NULL;
new->list = NULL;
printf("\n Inserting %c",new->value);
save->next = new;
i++;
}
return trie;
}
int main()
{
int num;
char *s = (char *)malloc(sizeof(char)*10);
trie = init_trie();
printf("\n Enter the number of words to enter into the trie ");
scanf("%d",&num);
while(num>0)
{
scanf("%s",s);
//printf("%s",s);
trie = insert_trie(s);
printf("\n Finished inserting the word %s into the trie \n",s);
num --;
}
return 0;
}
I get a segmentation fault due to the line nodepointer = nodepointer->list in insert_trie function ... Why ????
P.S : This is not homework.But i am trying to implement it. I just could not find the mistake .