Trying to make a hash table using smdb algorithm (since I hear it is wise to not attempt to write my own.) I'm sure I am doing it completely wrong. Did I mention I am new to C?
My hashFunction() % size is first returning a number like 35 the first time it is called, then on the 2nd call, 3rd call, 4th call..., it returns 65 ad infinitum. I am just using those numbers as arbitrary examples. After trying to figure it out with the debugger, I noticed the hashFunction is returning different longs, but they all end with the same last 2 numbers...like so...
4460735 4526335 4591935
So I guess this is why when I hash % size, I end up with the same output each time. Which goes against the idea of evenly distributed keys, right?
Go easy on me please. I know how savage people on SO can be.
#include <stdio.h>
#include <stdlib.h>
typedef struct node
{
char* str;
struct node* next;
}
node;
void insertItem(char* number, node** list);
unsigned long hashFunction(char* str);
int main(void)
{
int size = 100;
int index = 0;
node* buckets[size];
for (int i = 0; i < size; i++)
{
char c = i + 'A';
index = hashFunction(&c) % size;
insertItem(&c, &buckets[index]);
}
}
void insertItem(char* str, node** list)
{
node* newItem = malloc(sizeof(node));
newItem->str = str;
newItem->next = *list;
*list = newItem;
}
unsigned long hashFunction(char* str)
{
//sdbm hash function adapted (incorrectly?) from here: http://www.cse.yorku.ca/~oz/hash.html
unsigned long hash = 0;
int c;
while ((c = *str++))
hash = c + (hash << 6) + (hash << 16) - hash;
return hash;
}