C中给出负数的哈希函数

C中给出负数的哈希函数,c,hash,hashtable,C,Hash,Hashtable,我很好奇问题是我需要一个不同的哈希函数,还是我的代码有问题。我需要散列单词以存储在散列表中,函数似乎一切正常,但当我输入非常长的单词时,有些单词是45个字符,即使我要求返回一个无符号的long long,但我收到的散列是一个负数 这是代码,非常感谢您的帮助 unsigned long long hash(char* str); int main (void) { int numItems; char name[46]; printf("Please enter how

我很好奇问题是我需要一个不同的哈希函数,还是我的代码有问题。我需要散列单词以存储在散列表中,函数似乎一切正常,但当我输入非常长的单词时,有些单词是45个字符,即使我要求返回一个无符号的long long,但我收到的散列是一个负数

这是代码,非常感谢您的帮助

unsigned long long hash(char* str);

int main (void)
{
    int numItems;
    char name[46];
    printf("Please enter how many items will be in your hashtable:");
    scanf("%d", &numItems);

    for (int i = 0; i < numItems; i++)
    {
        int key = 0;
        printf("Please type a name to be entered into the Hashtable:");
        scanf("%s", name);

        //run the word through a hashfunction (simple hashfunction)

       //print the hash number
        key = hash(name);

        printf("%d\n", key);
    }
}
unsigned long long hash(char* str)
    {
        unsigned long hash = 5381;
        int c;
        for (int i = 0; i < strlen(str); ++i) 
            {
                c = (int) str[i];
                hash = ((hash << 5) + hash) + c; 
            }
        return hash;
    }
无符号长散列(char*str);
内部主(空)
{
int numItems;
字符名[46];
printf(“请输入您的哈希表中将包含多少项:”);
scanf(“%d”&numItems);
对于(int i=0;ihash=((hash函数
hash
返回一个
无符号long
,但将结果存储在
int

的类型更改为
无符号长
,并使用
%llu
格式说明符打印它

unsigned long long key = 0;
....
printf("%llu\n", key);

另外,
hash
函数中的
hash
变量应该具有类型
unsigned long long
,并且应该重命名该变量,以避免与函数名冲突。

可能重复的问题实际上是同一个问题。您的代码调用未定义的行为。并且您没有修复任何问题c在您的第一篇文章中,ommented on。您的哈希函数返回一个
无符号long-long
,它不能为负。但是,如果该值超出
int
的范围,通常情况下,则将其转换为(有符号)
int
具有实现定义的行为,其中可能包括生成负面结果。它有什么用,可以将哈希计算为
unsigned long
,但将其返回为
unsigned long
,然后将其分配给
int
?您应该重新设计您的接口以获得一致的结果。非常感谢您的支持我们的帮助回答了我的问题problem@TylerGotto .