0

So far I've been unable to get the dictionary to load properly in the speller problem set. The goal is to insert every word from the dictionary into a hash table.

Is what I'm doing in the the line where I set p=n (last line of the else loop) a valid way to make two node pointers point to the same node? I have a feeling that the problem may lie around there

// Loads dictionary into memory, returning true if successful, else false
bool load(const char *dictionary)
{
    // Open dictionary file
    FILE *file = fopen(dictionary,"r");
    if (file == NULL)
    {
        return false;
    }
    // Create memory space to read new word
    char bloc[LENGTH];
    
    // Read words one at a time until end of file is reached
    while (fscanf(file, "%s", bloc) != EOF)
    {
        // Create a new node and give as its value the new word
        node *n = malloc(sizeof(node));
        strcpy (n->word, bloc);

        // Generate hash value given new word
        unsigned int i = hash(n->word);

        // Insert new word into hash table
        if (index[i] == NULL)
        {
            index[i] = n;
        }
        else
        {
            node *p = malloc(sizeof(node));
            p->next = index[i]->next;
            while (p->next != NULL)
            {
                p = p->next;
            }
            p = n;
        }
    }
    fclose(file);
    return true;
}

1 Answer 1

1

The problem is this code:

    else
    {
        node *p = malloc(sizeof(node));
        p->next = index[i]->next;
        while (p->next != NULL)
        {
            p = p->next;
        }
        p = n;
    }

It serves no useful purpose. All it does is create a new node p and point it at the new node n that you just created. Worse, there's nothing to keep track of this new node.

Instead, it needs to be inserted into the linked lists tracked by index[]. (I am presuming that index[] is your main tree array to track the root nodes of each linked list.)

Simply put, the ->next pointer in the new node needs to point at the value in index[i], and then index[i] needs to be reset to point at the new node.

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 .