Tyler Gotto Tyler Gotto - 1 year ago 114
C Question

Hash Function in C giving a negative number

I am curious if the problem is that I need a different Hash Function or if there is a problem with my code. I need to hash words to store in a hash table, everything seems to be working good with the function but when I enter the words that are very long, some words are 45 characters, even though I am asking to get a unsigned long long returned to me, the hash I am receiving is a negative number.

Here is the code, your help is greatly appreciated.

unsigned long long hash(char* str);

int main (void)
int numItems;
char name[46];
printf("Please enter how many items will be in your hashtable:");
scanf("%d", &numItems);

for (int i = 0; i < numItems; i++)
int key = 0;
printf("Please type a name to be entered into the Hashtable:");
scanf("%s", name);

//run the word through a hashfunction (simple hashfunction)

//print the hash number
key = hash(name);

printf("%d\n", key);
unsigned long long hash(char* str)
unsigned long hash = 5381;
int c;
for (int i = 0; i < strlen(str); ++i)
c = (int) str[i];
hash = ((hash << 5) + hash) + c;
return hash;

Answer Source

The hash function returns an unsigned long long, but you're storing the result in an int.

Change the type of key to unsigned long long, and print it using the %llu format specifier.

unsigned long long key = 0;
printf("%llu\n", key);

Also, the hash variable inside of the hash function should have type unsigned long long, and that variable should be renamed so as not to clash with the name of the function.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download