【发布时间】:2020-10-18 01:54:01
【问题描述】:
我正在编写一个拼写检查单词的程序,但我的哈希函数没有为相同的单词返回相同的数字。
我的问题是我的哈希函数如何不为相同的输入返回相同的哈希。
这是我的问题的一个最小的、可重现的示例:
// Implements a dictionary's functionality
#define HASHTABLE_SIZE 65536
// Represents a node in a hash table
typedef struct node
{
char word[LENGTH + 1];
struct node *next;
}
node;
// Number of buckets in hash table
const unsigned int N = HASHTABLE_SIZE;
// Hash table
node *table[N];
unsigned int totalWords = 0;
// Hashes word to a number
unsigned int hash(const char *word)
{
unsigned int hash_value;
for (int i=0, n=strlen(word); i<n; i++)
hash_value = (hash_value << 2) ^ word[i];
return hash_value % HASHTABLE_SIZE;
}
【问题讨论】:
-
提供示例输入、预期输出、实际输出并描述您的程序试图做什么。
-
贴出的代码无法编译!首先,函数:
hash()在编译器知道其签名之前被调用。建议在第一个函数之前插入hash()的原型 Next:node *table[N];结果:untitled1.c:26:7: error: varially modified 'table' at file scope 然后你的本土文件:directory.h需要发布其内容 -
编译时,始终启用警告,然后修复这些警告。 (对于
gcc,至少使用:-Wall -Wextra -Wconversion -pedantic -std=gnu11)注意:其他编译器使用不同的选项来产生相同的结果
标签: c hashtable cs50 hash-function