我试图在C中实现哈希表来存储英文单词。所以我在互联网上搜索一些最好的非加密哈希函数。其中一些是 Murmurhash,Seahash,xxHash ,但它们似乎都很难实现。所以我搜索了一些较简单的,然后我发现了 DJB2,sdbm,输了。在实现sdbm时我得到了这个
try.c:12:18: error: using the result of an assignment as a condition without
parentheses [-Werror,-Wparentheses]
while (c = *str++)
~~^~~~~~~~
try.c:12:18: note: place parentheses around the assignment to silence this
warning
while (c = *str++)
^
( )
try.c:12:18: note: use '==' to turn this assignment into an equality
comparison
while (c = *str++)
^
==
try.c:26:31: error: passing 'char *' to parameter of type 'unsigned char *'
converts between pointers to integer types with
different sign [-Werror,-Wpointer-sign]
unsigned long hash = sdbm(argv[1]);
^~~~~~~
2 errors generated.
我的代码是
#include <cs50.h>
#include <string.h>
#include <stdio.h>
static unsigned long
sdbm(str)
unsigned char *str;
{
unsigned long hash = 0;
int c;
while (c = *str++)
hash = c + (hash << 6) + (hash << 16) - hash;
return hash;
}
int main(int argc,char *argv[])
{
if(argc!=2)
{
printf("Enter the second command line argument\n");
return 1;
}
unsigned long hash = sdbm(argv[1]);
printf("The returned hashcode is %lu\n", hash);
}
如果您还可以帮我使用Murmurhash,Seahash或xxHash,请执行此操作。
答案 0 :(得分:1)
Oups!带有简单参数列表的此函数定义是一个过时的功能:
static unsigned long
sdbm(str)
unsigned char *str;
{
标准方式是(至少从80年代后期开始)是使用原型定义:
static unsigned long
sdbm(unsigned char *str)
{
现在出现错误:
while ((c = *str++))
...
括号告诉编译器您测试了赋值的结果值。
unsigned long hash = sdbm((unsigned char *) argv[1]);
只强制转换为预期的指针类型。