blog

My blog at www.shimmy1996.com

git clone git://git.shimmy1996.com/blog.git

2014-07-11-the-quest-to-hash-table.en.md (1899B)

    1 +++
    2 title = "The Quest to Hash Table"
    3 draft = false
    4 date = 2014-07-11
    5 slug = "the-quest-to-hash-table"
    6 +++
    7 
    8 Several mistakes I made when I tried to write a hash program using C.
    9 
   10 1.  A pointer that points to a pointer that points to a pointer that points to a pointer that points to a...
   11 
   12     Generating an array of pointers is the core step when creating a hash table, but the malloc function and the pointer part can be a little bit confusing. There are, however, general rules for this:
   13 
   14     -   How many `*` s we put before a variable tells us how many dereferences we need to get the original type we want. If we want to make an array of `*node` (or some other pointer/type of variables), then we should add one extra `*` when declaring the array: `node **node`;
   15     -   General formula for using malloc to collect an array containing `NSLOT` pointers to node: `array_of_pointers = (node **)malloc(NSLOTS * sizeof(node *))`. The rule still holds if we add more `*` to each node or subtract `*` simultaneously: `array_of_pointers = (node ***)malloc(NSLOTS * sizeof(node **))`.
   16 
   17     Do note that `array_of_pointers = (node **)malloc(NSLOTS * sizeof(node *))` is equivalent to `node **array_of_pointers = malloc(NSLOTS * sizeof(node *))`.  Don't be afraid to use index on objects created this way: it's fine...
   18 
   19 2.  Be mindful when you add node to one of the linked lists, more so when you are freeing it. Do note that, when you are checking whether a key is already present in the hash table, if a the key already exists in the hash table, you will have an extra copy of the key. Make sure it is freed. Also do not forget to free the key afterwards.
   20 
   21 Apologies if this seemed unfinished XDD.
   22 
   23 I started writing this stuff five months ago and just did not got a chance to finish it till now... Tried to pull off some points from the original code I had, but this is pretty much all I got now XDD.