0

Well I'm not even sure how I can test this but I have a strong feeling that my speller is not even loading the words on to my dic. Can anyone tell me why?

The program compiles and runs.

// Loads dictionary into memory, returning true if successful else false
bool load(const char *dictionary)
{
    // Initialize hash table
    for (int i = 0; i < 25; i++)
    {
        hashtable[i] = NULL;
    }

    // Open dictionary
    FILE *file = fopen(dictionary, "r");
    if (file == NULL)
    {
        unload();
        return false;
    }
    
    // Buffer for a word
    char word[LENGTH + 1];
    
    // Create head of linked list
    node *head = malloc(sizeof(node));

    // Insert words into hash table
    while (fscanf(file, "%s", word) != EOF)
    {
        //change pointer of the new node to the already existing beginning of link list node
        head->next = hashtable[hash(word)];

        //then change the hashtable's first pointer to the new_node
        hashtable[hash(word)] = head;

        // Allocate space for node
        node *new_node = malloc(sizeof(node));

        // Check for space
        if (new_node == NULL)
        {
            unload();
            return false;
        }
        else
        {
            // Copy node
            strcpy(new_node->word, word);
    
            // Hash word and insert into hashtable
            int hash_key = hash(new_node->word);
            head = hashtable[hash_key];
 
            // Insert node into linked list
            new_node->next = head;
            head = new_node;
        }
    }

    // Close dictionary
    fclose(file);

    // Indicate success
    return true;
}

1 Answer 1

0

Use i < N instead of i < 25, with N being the number of bins. Though, in this case, it does not matter, since hashtable probably is a global array variable, and global variables are always initialised (if not explicitly to a specific value, then implicitly to all bytes 0).

I totally don't get the meaning of the head variable, and the meaning of the first node that does not contain a word. Use hashtable[hash_key], not head, for installing new_node. Since head contains just a copy of the value of hashtable[hash_key], changing its value has no effect on the original value.

You must log in to answer this question.

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