1

I have been stuck on the load part of the speller exercise for the tries table. I have gone through a lot of the existing questions and come to the following code:

while (fscanf(file, "%s", word) != EOF)
{
    // TODO
    node *ptr=root;
    for (int l=0; l<LENGTH+1; l++)
    {       
        if (isalpha(word[l]))
        {
            // lower case:
            word[l] = tolower(word[l]);
            if (ptr->children[word[l]-'a']==NULL)
            {
                ptr->children[word[l]-'a']= malloc(sizeof(node));
            }
            ptr = ptr->children[word[l] - 'a'];
        }
    }
}

However, when I run through the code in the debug mode, I see that my ptr keeps getting reset after the line ptr = ptr->children[word[l] - 'a'] is run. is this expected? I was expecting the node ptr to be accumulating as the for loop continues... or in fact ptr here is only a temp one and really I should set up some other node?

1
  • what do you ptr keeps getting reset? what value is ptr reset to?
    – stensal
    Feb 9 '19 at 19:51
1

Yes, it would reset on each pass through the while loop, but not through the for loop. Simply put, ptr is created at the start of each pass through the while loop and then destroyed at the end of each pass. This is called scope of a variable.

However, that doesn't mean that the data is being lost. The code is inserting the data in the tree that starts at root, so that shouldn't be a problem.

I do see a problem in how the nodes are being created. Since the code uses malloc, the node elements, particularly the children pointers, are NOT being initialized. That means that those pointers contain garbage data, not NULL, and not valid addresses. You should either manually initialize the pointers or use calloc().

As for the trie, you could create a recursive for loop to walk the trie and print out data to convince yourself that it exists, or look at the trie in debug mode.

If this answers your question, please click on the check mark to accept. Let's keep up on forum maintenance. ;-)

You must log in to answer this question.

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