I'm starting to work with tries in C and I made this really simple program, but somehow it crashes. I don't know why but if you could take a look at my code and tell me that would be great.
#include <stdio.h>
#include <stdlib.h>
#include <cs50.h>
#include <string.h>
typedef struct node
{
bool is_word;
struct node* children[27];
}
node;
node* root;
int main()
{
root->children[0]=NULL;
}
The problem lies here.
node *root;
You have declared root but you have not defined it. By default this contains some garbage address or being global a NULL, which is illegal to access and hence the program crashes.
Initialise your root to the first node of the trie and then use it further.
Doing this operation-
root->children[0] = NULL
translates to someGarbageValue/NULL -> children[0] = NULL //makes no sense. Initialise your root to your first node.
For initialising the root you can allocate memory to it.
root = (node *)malloc(sizeof(node));
this will allocate the memory from the heap, and malloc will store the starting address of that allocated memory into the root node pointer.
Don't forget to free this memory to avoid memory leaks when you are done with it.
free(root)