0

When I load the dictionary, I add the words to the hash table, by calling the hash function to calculate the bucket ID, then add hash function to actually insert it into the list.

Inside the addhash function, I store the value, and then print it to check it stored the correct word which it seems to do.

int addhash (const char *word, unsigned int hash_num)
{
    //create temp node
    node *newnode = malloc(sizeof(node));
    if (newnode == NULL)
    {
        //error memory allocation fail
        return 1;
    }
    strcpy (newnode->word,  word);  //store word in temp
    newnode->next = NULL;  //null pointer for next

    //if hash entry is null, store the temp at this location
    if (table[hash_num] == NULL)
    {
        table[hash_num] = newnode;
        printf("word stored from dictionary\n");
        printf("'%s'\n",table[hash_num]->word);
        free(newnode); //free the memory that was allocated
    }
    //if word is duplicate, ignore
    else if (table[hash_num]->word == word)
    {
        printf("word: %s already in dict\n", table[hash_num]->word);
    }
    else    // insert word by chaining
    {
        //new node point to where head is pointing
        newnode->next = table[hash_num]->next;
        table[hash_num]->next = newnode;
        printf("word stored from dictionary\n");
        printf("'%s'\n",table[hash_num]->word);
    }

    return 0;
}

I was getting errors finding matches with the dictionary so to test the known values in the hash table, I printed the words stored in the hash table. If i print directly after the function call addhash, each word are listed is ' ' rather than the word that I thought had stored.

//store word
addhash(word, cHash);
printf("Inside Load, after add hash, table[%u]->word = '%s'\n", cHash, table[cHash]->word);

And this was my terminal output.

cat hash at 22038
word count = 1
word stored from dictionary
'cat'
Inside Load, after add hash, table[22038]->word = ''
caterpillar hash at 27919
word count = 2
word stored from dictionary
'caterpillar'
Inside Load, after add hash, table[27919]->word = ''

MISSPELLED WORDS

Inside check, table[22443]->word  = '(null)'
Inside search, table[22443]->word  = '(null)'
A
Inside check, table[22038]->word  = ''
Inside search, table[22038]->word  = ''
cat
Inside check, table[28157]->word  = '(null)'
Inside search, table[28157]->word  = '(null)'
is
Inside check, table[3440]->word  = '(null)'
Inside search, table[3440]->word  = '(null)'
not
Inside check, table[22475]->word  = '(null)'
Inside search, table[22475]->word  = '(null)'
a
Inside check, table[27919]->word  = ''
Inside search, table[27919]->word  = ''
caterpillar
0

I think i may have figured it out. I was freeing the new node in the addhash function, thus wiping the word saved in the node. I do think freeing needs to happen until unloading the files in the unload function.

You must log in to answer this question.

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