结构行为

时间:2014-04-01 16:43:21

标签: c hash struct

混淆了为什么我的结构哈希表表现如何。

我的结构:

typedef struct words {
    const char *word;
    int hitCount;
} words;

我从文档中获取一个单词并生成哈希值,使用线性探测进行冲突。如果找到相同的单词我hitCount ++ else我找到空格并覆盖表中的空结构。

这是我的方法:

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++;
    }
}

到目前为止,我用一个简单的.txt测试了它,其中包含15x“test”和3x“hello”:

Test Test Test
Test Test Test
Test Test Test
Test Test Test
Test Test Test
Hello Hello Hello

并输出以下内容:

hello:15
hello:3

而不是预期的:

test:15
hello:3

由于某些原因我无法看到它覆盖保存在表格中相应位置的“测试”。

使用printf()表明,只要添加第一个“hello”,它就会擦除“test”,即使正确的索引被解析为add()并且它与“test”的不同。 / p>

我希望我已经包含了错误代码的来源,并且我已经提供了足够的信息。

谢谢!

Ps :(所有不在字母表中的内容都被删除,解决方案必须在C中)

1 个答案:

答案 0 :(得分:2)

您没有复制inputWord,而是将指针存储到其所包含的内存中。 因此,当您扫描下一个单词时,内存会发生变化。所有表条目最终都会指向同一个单词。

您需要执行ht[index].word = strdup(inputWord);或类似的事情。