gpt4 book ai didi

c - 哈希函数在同一输入上返回随机值

转载 作者:行者123 更新时间:2023-11-30 15:42:57 25 4
gpt4 key购买 nike

我正在研究简单的字符串哈希表。我使用相同的输入运行程序,在某些情况下哈希会返回一个随机数。

这是我的代码:

LIST *table[1000];

void init()
{
for(i=0;i<1000;i++) //set table to NULL
table[i]=NULL;
}

int hash(char *array) //hash function
{
int hash=0;
hash=array[0]+strlen(array)+array[strlen(array-1)];
hash=hash%1000;
printf("%d\n",hash); //print of hash
return hash;
}

void add(char *arr)
{
char *str = (char *) malloc(sizeof(char) * strlen(arr)+1); //
strcpy(str,arr);
int h=0;
h=hash(str);
LIST *f=table[h];
//...... rest of the code
}


int main()
{
init();
add("/");
add("+");
add("-");
return 0;
}

And output is:
141
137
139
After rerun output is:
110
106
108

有人知道这个哈希函数有什么问题吗?

最佳答案

我猜,strlen(array-1) 是罪魁祸首。

您不知道 array - 1 中的字符是什么,因此有时可能会返回 0。有时它可能会返回 strlen(array) + 1

因此,您将 array[0] 添加到哈希值,有时您会在字符串之外添加一个字符,array[strlen(array) + 1] .

关于c - 哈希函数在同一输入上返回随机值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19987449/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com