0

I was trying to implement hash table in C to store English words. So I was searching through the internet to some of the best non-cryptographic hash functions. Some of them are Murmurhash, Seahash, xxHash but they all seemed very difficult to implement. So I searched for some of the simpler ones then I found out about the DJB2, sdbm, lose lose. On implementing sdbm I got this

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. 

My code was

#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);
}

If you can also help me with Murmurhash, Seahash or the xxHash, please do so.

Jonathan Leffler
  • 730,956
  • 141
  • 904
  • 1,278

1 Answers1

1

Oups! This function definition with a simple parameter list is an obsolescent feature:

static unsigned long
sdbm(str)
unsigned char *str;
{

Standard way is (at least since the late 80's) is to use a prototype definition:

static unsigned long
sdbm(unsigned char *str)
{

Now for the errors:

while ((c = *str++))
    ...

the parentheses tell the compiler that you test the result value of the assignation.

unsigned long hash = sdbm((unsigned char *) argv[1]);

just forces a cast to the expected pointer type.

Serge Ballesta
  • 143,923
  • 11
  • 122
  • 252