HiveBrain v1.2.0
Get Started
← Back to all entries
patterncMinor

Dictionary load function using hash table

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
functionhashusingloaddictionarytable

Problem

This loads a dictionary text file into memory to be used as part of a spell checker. It's part of a larger program, but I wanted general comments so I can clean it up further.

#define TABLESIZE 500
#define LENGTH 45

bool load(const char* dictionary)
{
    //initiate hash table
    node* hashtable[TABLESIZE];    

    //open dictionary and check
    FILE* dict = fopen(dictionary, "r");
    if (dict == NULL)
    {
        printf("Could not open file.");
        return false;
    }

    //initiate variable to store current word
    char* dword = calloc(LENGTH+ 1,sizeof(char)); 

    //read the file
    while(fscanf(dict, "%s", dword) != EOF)
    {
        //if there is a word, create node and put word in it
        node* new_node = malloc(sizeof(node));
        strcpy(new_node->word,dword);

        //find spot in hash table and put it in that bucket
        unsigned int hashkey= 0;
        for (int counter = 0; dword[counter]!= '\0'; counter++)
        {
            hashkey = (hashkey*dword[counter] + dword[counter] + counter)%TABLESIZE;
        }

        //check if spot in table exists; if not, start the linked list
        if (hashtable[hashkey] == NULL)
        {    
            hashtable[hashkey] = new_node;
            new_node->next = NULL;
        }
        //otherwise made current node the first, shift rest over
        else
        {
            new_node->next = hashtable[hashkey];
            hashtable[hashkey] = new_node;
        }       
        //count words for later use
        nwords++;

    }

    fclose(dict);
    return true;    
}

Solution


  • Your constants could be named slightly differently; consider TABLE_SIZE and MAX_WORD_LENGTH.



  • You could also rename dictionary to better indicate that it's a file path and not a dictionary object.



  • Consider printing error output to stderr: fputs(stderr, ...) or fprintf(stderr, ...).



  • You're using a global nwords, but a local hashtable; this looks to me like a scoping error. You could consider just making a new struct.

Context

StackExchange Code Review Q#58228, answer score: 5

Revisions (0)

No revisions yet.