Reputation: 541
Confused as to why my hash table of structs is behaving how it is.
My struct:
typedef struct words {
const char *word;
int hitCount;
} words;
I take a word from a document and generate a hash value, use linear probing for collisions. If the same word is found I hitCount++ else I find space and overwrite the empty struct in table.
Here's my method to do this:
void add (char *inputWord, int index, int tableLength) {
while (hashTable[index].word != "0") {
if (strcmp(hashTable[index].word, inputWord) == 0) {
hashTable[index].hitCount++;
break;
} else {
index = ++index % tableLength;
}
}
if (hashTable[index].word == "0") {
hashTable[index].word = inputWord;
hashTable[index].hitCount++;
}
}
So far I've tested it with a simple .txt that contains 15x"test" and 3x"hello":
Test Test Test
Test Test Test
Test Test Test
Test Test Test
Test Test Test
Hello Hello Hello
and it outputs the following:
hello:15
hello:3
instead of the expected:
test:15
hello:3
For some reason that I can't see it overwrites the "test" saved in the appropriate location in the table.
Using printf() has shown that as soon as it adds the first "hello" it wipes the "test" over even though the correct index is being parsed to add() and it's different to that of "test".
I hope I've included the source of the incorrect code and I've given enough information.
Thanks!!
Ps: (Everything that isn't in the alphabet is stripped and solution has to be in C)
Upvotes: 0
Views: 56
Reputation: 35580
You are not copying inputWord
, you are storing the pointer to the memory it is contained in.
So when you scan the next word, the memory changes. All the table entries will end up pointing to the same word.
You need to do a ht[index].word = strdup(inputWord);
or something similar.
Upvotes: 2