【问题标题】:Hash function precision issue哈希函数精度问题
【发布时间】: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


【解决方案1】:

您的fscanf 写入word 指向的此内存块的外部。

    char *word = malloc(LENGTH);  // this is too small to hold a word + '\0'
    ...
    while (fscanf(dicfile, "%s", word) != EOF)
    {

将大小增加到LENGTH+1

【讨论】:

  • 嘿!我不知道为什么,但它仍然不起作用? :(
  • 请使用 pastebin.com 在此处发布您的最新代码?
【解决方案2】:

散列函数中的hash_value 未初始化,它会造成内存破坏,从而导致不可预测的结果。来自引用的帖子:

unsigned int hash = 0;

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-03-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多