0

I'm trying to implement load in pset5, however I'm having trouble putting them into the hash table. What I have is the following: I believe I should be getting an output of the below when I test it with dictionary/small

    hello cat
    cat

However, what I'm actually getting is

    hello cat
    caterpillar.

The below is my code:

    while(fgets(line, LENGTH + 1, dic) != NULL)
{

    hash = hashFunction(line[0]);
    node* newNode = malloc(sizeof(node));
    if (newNode == NULL)
    {
        printf("not enough space\n");
        return false;
    }
    newNode->next = NULL;
    newNode->word = line;
    if(table[hash] == NULL)
    {

        table[hash] = newNode;
        printf("hello %s", table[hash]->word);
    }
    else
    {

        printf("%s", table[hash]->word) //shouldn't this still be cat? I haven't done anything with table[hash] yet, but it's coming out as caterpillar;

    }

}
0

There are several issues. I'll touch on the biggest ones I see.

First, there's this: newNode->word = line; It doesn't copy the string, it copies the address of the first character in the string. Ultimately, everything will point to the address of line and will contain only the last word entered. You need to use strcpy() or one of it's cousins to actually copy a string.

Next, there is no code to handle the case where there is already a word in the tree for a given hash code.

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 .