【发布时间】:2021-01-12 13:18:54
【问题描述】:
我需要为给定的单词生成一个哈希值。哈希值需要是确定性的,或者同一个词的值相同,但是如果给定的词有不同的情况,哈希值会改变。 所以我的目标是在散列函数中将给定的单词(const char)转换为小写,以便无论大小写如何都始终获得相同的散列码。 我有以下代码:
#include <stdio.h>
#include <ctype.h>
#define LENGTH 45
const unsigned int N = 7703;
// Prototypes
unsigned int hash(const char *word);
int main()
{
int s;
char *text;
text = "aardvark's"; //given word this can have upper and lower cases
s = hash(text);
printf("text: %s\n",text);
printf("hash or text: %d\n",s);
return 0;
}
unsigned int hash(const char *word) // the given word is constant char
{
unsigned long h;
unsigned char *str = (char*)word;
h = 0;
while(*str != '\0')
{
*str = tolower(*str); //trying to convert to lower cases
h = (h * LENGTH + *str) % N;
str++;
}
return h;
}
我已经尝试了上述以及不同的组合,但我不断收到错误,主要错误是“分段错误核心转储”,但使用不同的代码排列我得到错误:“从整数中生成指针而不进行强制转换”。 你能建议如何解决这个问题吗?因为我被卡住了,非常感谢。
【问题讨论】:
-
你创建了一个字符串字面量,巫婆通常存储在只读存储器中。然后,您尝试在散列函数中修改它(破坏性)。这就是你得到 Seg Fault 的原因。
标签: c