【发布时间】:2016-02-09 02:21:10
【问题描述】:
我目前正在阅读 K&R 的“The C Programming Language”一书。在“结构”章节中,在“表查找”(第 144 页)的子主题下,我找到了这个哈希生成函数
#define HASHSIZE 101
struct nlist {
struct nlist *next;
char *name;
char *defn;
}
static struct nlist *hashtab[HASHSIZE];
unsigned hash(char *s)
{
unsigned hashval;
for (hashval = 0; *s != '\0'; s++)
hashval = *s + 31 * hashval;
return hashval % HASHSIZE;
}
我不明白这个函数实际上是做什么的。
我认为它会为给定的字符串 (char *s) 生成一个唯一地址(作为 hashtab 上的索引)。
但我认为可以给两个不同的字符串赋予相同的索引,因为 (hashval % HASHSIZE) 是给定的地址 (203 % 101 = 405 % 101 = 1)。
为什么 HASHSIZE 101 和 hashval 乘以 31?为什么不是 100 或 32?
【问题讨论】: