antonpug antonpug - 7 months ago 32
C Question

Trying to write a HASH TABLE in C, am I doing the right thing here?

So I have a hash function already given to me.

I have an object struct of:

OBJKT *o_hash_next;
OBJKT *o_hash_prev;
... bunch of other stuff

I also have the hash array declared in the header file: OBJKT *hash_tbl[hsize];

The method that is supposed to add a given OBJKT to the hash takes in a hash key, and the OBJKT we are adding.

So this is what I am not sure I am doing correctly:

void insert_in_hash(int hashindex, OBJKT *thisObject)
*thisObject->o_hash_next = *hash_tbl[hashindex];
*hash_tbl[hashindex] = *thisObject;

Does this seem correct? I am trying to set the previous/next pointers and then add the thisObject into the hash.


Looks about right. For a hashtable you don't necessarily need a doubly-linked list, though.

Don't forget to zero your hash_tbl to start.

And you may find it useful to have the hashvalue directly in your OBJKT entries, to speed searches.


Based on unexplored's comments (those darn "*" characters), it probably should look like this:

void insert_in_hash(int hashindex, OBJKT *thisObject)
   thisObject->o_hash_next = hash_tbl[hashindex];
   thisObject->o_hash_prev = NULL;
   hash_tbl[hashindex] = thisObject;