0

I'm having trouble with my load function... I had it working previously, but after changing some stuff and dealing with the check, I ran into this issue and can't seem to figure it out...

Every time I load a new word, the words that were previously added into the hash table gets written over (with the new word). I created a test dictionary, with 26 words, going from apple-zebra, and after the dictionary loads, every word in my hashtable[i], where i = 0-25 is zebra...

Can someone spot check my work here? I appreciate it.

/**
 * Implements a dictionary's functionality.
 */

#include <stdbool.h>
#include <stdio.h>
#include <stdlib.h>
#include "dictionary.h"
#include <ctype.h>
#include <strings.h>

typedef struct node
{
    char word[LENGTH +1];
    struct node* next;
}node;

node* hashtable[26];

int getHashIndex(const char *c)
{
    int x = (tolower(c[0]) - 'a') % 26;
    return x;
}

int noWords = 0;

//Loads dictionary into memory. Returns true if successful else false.

bool load(const char *dictionary)
{

    FILE *file = fopen(dictionary, "r");

    node* nodePointer = malloc(sizeof(node));
        if (nodePointer == NULL)
        {
            unload();
            return false;
        }

    while (fscanf(file, "%s", nodePointer -> word) != EOF)
    {
        int firstLetter = getHashIndex(nodePointer -> word);

        if (hashtable[firstLetter] == NULL)
        {
            hashtable[firstLetter] = nodePointer;
            hashtable[firstLetter]-> next = NULL;
            noWords++;
        }
        else if(hashtable[firstLetter] != NULL)
        {
            nodePointer -> next = hashtable[firstLetter] -> next;
            hashtable[firstLetter] = nodePointer;
            noWords++;
        }
    }

    if(feof(file))
    {
        return true;
        fclose(file);
    }
    return false;
    fclose(file);
}
0

You are only mallocing one node in load, so each word you read in, goes into that node. Hence, when you look at your table, all the words are the very last word because they all point to that same node.

Be sure to malloc a new node for each word. (in your loop)

2
  • Thanks @curiouskiwi! That solved the issue. :D – Kelby Lu Apr 19 '17 at 16:18
  • @KelbyLu Glad to hear. please vote and accept my answer so this question will be removed from the open list. – curiouskiwi Apr 19 '17 at 21:26

You must log in to answer this question.

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