【问题标题】:Implement non-cryptographic hash functions in C在 C 中实现非加密哈希函数
【发布时间】:2018-07-12 20:58:50
【问题描述】:

我试图在 C 中实现哈希表来存储英文单词。所以我在互联网上搜索了一些最好的非加密哈希函数。其中一些是Murmurhash、Seahash、xxHash,但它们似乎都很难实现。所以我搜索了一些更简单的然后我发现了DJB2,sdbm,loose loss。在实施 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,请这样做。

【问题讨论】:

  • 关闭-Wparentheses 警告,或者按照第一条错误消息告诉您的操作。
  • 对于最后一个错误:sdbm(str) unsigned char *str;-> sdbm(str) char *str; 或更好的sdbm(unsigned char *str)。 ;
  • while (c = *str++) -> while ((c = *str++) != 0) .
  • 您在一个问题中提出了多个问题。太宽泛了。

标签: c hash cs50 murmurhash


【解决方案1】:

哎呀!这个带有简单参数列表的函数定义是一个过时的特性:

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]);

只是强制转换为预期的指针类型。

【讨论】:

    猜你喜欢
    • 2020-08-08
    • 2021-01-23
    • 2013-05-05
    • 2016-03-25
    • 2017-05-02
    • 2010-09-06
    • 2015-02-02
    • 2021-11-19
    相关资源
    最近更新 更多