0

I've declared a trie in the .h file with

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

and also declared

    node* root;

Above the .c file. I've always receive a feedback of the fault. I think the problem lies in the "if (ptr->children[key_i] == NULL)" line but didn't know what exactly is the problem, anyone please help and give advice please.

bool load(const char* dictionary)
{
    FILE* dict = fopen(dictionary,"r");
    if (dict == NULL)
        return false;

while (!feof(dic))
{
    char* word = malloc(sizeof(char[LENGTH+1]));
    fscanf(dict, "%s", word);
    printf("%s\n", word);
    node* ptr = root;
    for (int i = 0, n = strlen(word); i < n; i++)
    {
        int key_i = toupper(word[i] - 'A');
        if (ptr->children[key_i] == NULL)
        {
            node* new = malloc(sizeof(node));
            ptr->children[key_i] = new;
            ptr = ptr->children[key_i];
            if (i == (n - 1))
            {
                ptr->is_word = true;
            }
        }
        else
        {
            ptr = ptr->children[key_i];
            if (i == (n -1))
            {
                ptr->is_word = true;
            }
        } 
    }
}

2 Answers 2

0

As @Billy.Ljm pointed out you have a problem with your key. The correct assignment would be int key_i = toupper(word[i]) - 'A'; BUT this is still not the right way. First of all you should also check if the read letter is an apostrophe ' or a letter. Moreover the specification says that all letters are lowercase, so you don't have to convert it to uppercase and then subtract the 'A'. Also your if condition shouldn't use the key_i variable, because you have only 26 children nodes, and if an apostrophe ' is read, or the terminating null byte '\0' even if you subtract 'A' or even 'a' it will give you a number outside the allocated space.

0

Your segmentation fault should be due to int key_i = toupper(word[i] - 'A'). You subtract the 2 letters to get an int, then you try to toupper() it.

Another problem is in your struct, struct node* children[27] is a node**, that's a pointer to a pointer. You are declaring an array of pointers which I don't think is what you intended.

You must log in to answer this question.

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