0

I have been looking at other questions like mine but none of the answers have helped me so im asking myself. I have been debugging for awhile and im pretty sure the problem is that im not accessing the nodes which contain the loaded dictionary but I don't know how to solve it.

Global Variables:

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

struct node* trie;

Load function:

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

    node *trie = malloc(sizeof(node));
    int value;

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

        for (char letter = fgetc(dictionary_file); letter != '\n'; letter = fgetc(dictionary_file))
        {
            if (letter == 39)
            {
                value = 26;
            }
            else
            {
                value = tolower(letter) - 'a';
            }

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

Check function:

bool check(const char* word)
{
    trie = malloc(sizeof(node));
    struct node *current;
    current = trie;
    int index;

    for (int i = 0; i < strlen(word); i++)
    {
        if (word[i] == 39)
        {
            index = 26;
        }
        else
        {
            index = tolower(word[i]) - 'a';
        }

        if (current->children[index] == NULL)
        {
            return false;
        }
        else
        {
            current = current->children[index];
        }
    }
    if (current->is_word == false)
    {
        return false;
    }
    return true;
}

1 Answer 1

0

I found my problem. I was making my node declared globally a local variable in both my load and check function because I used the code:

node *trie = malloc(sizeof(node));

instead of:

trie = malloc(sizeof(node));

I also got rid of the line of code in my check function

trie = malloc(sizeof(node));

because it was overwritting the global variable trie.

1
  • Good catch. Yes, declaring trie in check would've overwritten your original declaration yielding an empty trie to check.
    – ronga
    Commented Aug 10, 2016 at 8:02

You must log in to answer this question.

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