c - 哈希函数精度问题
问题描述
我正在编写一个拼写检查单词的程序,但我的哈希函数没有为相同的单词返回相同的数字。
我的问题是我的哈希函数如何不为相同的输入返回相同的哈希值。
这是我的问题的一个最小的、可重现的示例:
// 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_value
在散列函数中未初始化,它会造成内存破坏,从而导致不可预测的结果。从引用的帖子:
unsigned int hash = 0;
推荐阅读
- filebeat - Filebeat 在尝试收获 3 次后死亡 (max_retries)
- c# - 在 C# 中从 Visual Studio 2015 访问操纵杆控件
- qt - 如何将 QCommandLineParser 的实例化传递给 Qt 中的函数?
- python - PipeDrive - 使用 WebHooks 时如何避免循环?
- visual-studio-code - 如何在 VSCode 的拆分编辑器中打开文件?
- linux - 使用 sed 和 IFS 替换 while 循环内的值
- laravel - 有没有办法在 laravel 的不同数据库中对用户进行身份验证?
- javascript - 在列表顶部显示选择选项
- jenkins - 是否可以通过 jenkins jobdsl 将 xml 直接导入 freestylejob
- python - 如何在文件的单行中打印长字符串