1

I thought my trie was finally working but when I ran it in the debugger using a dictionary containing the words cat and caterpillar, current->children[value] always equalled NULL. I have spent the last hour trying to figure out why but i'm stuck.

bool load(const char* dictionary)
{
// opens dictionary file
FILE* dictionary_file = fopen(dictionary, "r");

typedef struct node
{
    bool is_word;
    struct node *children[27];
}
node;

// node for memory allocation
node *trie = malloc(sizeof(node));

// iterates through the trie
while (fgetc(dictionary_file) != EOF)
{
    fseek(dictionary_file, -1, SEEK_CUR);

    for (char letter = fgetc(dictionary_file); letter != '\n'; letter = fgetc(dictionary_file))
    {
        int value = tolower(letter) - 'a'; // gives letter the correct index and assigns it to value

        if (trie->children[value] == NULL)
        {
            trie->children[value] = malloc(sizeof(node));
            trie = trie->children[value];
        }
        else
        {
            trie = trie->children[value];
        }
    }
    trie->is_word = true;    
}
fclose(dictionary_file);
return true;

}

3
  • You need to figure out a way to remember the address to your root node, since you want to come back to it each time you start a new word. – dLopez Aug 8 '16 at 20:19
  • thanks @dLopez, pretty sure my trie works now – Ben Aug 8 '16 at 21:00
  • Perfect! You can now answer your own question, then after a couple days mark it as correct! This way we help keep the unanswered question pool clean. – dLopez Aug 8 '16 at 22:45
0

I didn't have a variable declared inside the while loop that stored the value of trie so trie wasn't pointing to the root node at the start of a new word.

solution:

while (fgetc(dictionary_file) != EOF)
{
    fseek(dictionary_file, -1, SEEK_CUR);
    node *current = trie;

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .