Search code examples
chashtablechaining

Initialize new Hash Table, pointers issue


I have this exercise for homework that follows:

Consider the following definition to represent dynamic hashtables with collision treatment chaining.

typedef struct entry{
   char key[10];
   void *info;
   struct entry *next;
}   *Entry;

typedef struct hashT{
   int hashsize;
   Entry *table;
}   *HashTable;

Define `HashTable newTable(int hashsize) note that the memmory necessary must be allocated and that all table entrys must be initialized with empty list.

My proposition is this:

HashTable newTable(int hashSize){
   Entry *table = malloc(sizeof((struct entry)*hashSize));
   HashTable *h = malloc(sizeof(struct hashT));
   h->hashSize = hashSize;
   h->table = table;
   return h;
}

im pretty sure the logic is correct. my problem is with pointers. for example, sometime I see (char *), or in this case (table *) before the malloc function... Is this necessary?

and for the return, should I return h, or *h? and whats the difference?

thank you


Solution

  • Firstly,

    Entry *table = malloc(sizeof((struct entry)*hashSize));
    

    will be

    Entry table = malloc(sizeof(struct entry)*hashSize);
                               ^^^    
                               Look at the parentheses here.
    

    Also you will do the same change over here,

    HashTable h = malloc(sizeof(struct hashT));
    

    Same goes with HashTable. You forgot that you have hidden the pointers inside typedef which you shouldn't.

    With the above mentioned changes the code will be

    HashTable newTable(int hashSize){
       Entry table = malloc(sizeof(struct entry)*hashSize);
       HashTable h = malloc(sizeof(struct hashT));
       h->hashSize = hashSize;
       h->table = table;
       return h;
    }
    

    And Dont hide pointer behind typedef.(Wish I could write this in red color but yes this will save you from many many problems).

    What is the type of Entry*?

    It is of type struct entry **. Here in your case you don't need it while allocating. It will be an overkill if you do so.

    What is the difference between h and *h?

    Well typewise h is of type struct hashT** and so *h will be of type struct hashT*.

    What shall you do next?

    • Compile all your code with warnings enabled. gcc -Wall -Werror progname.c
    • Check the return value of malloc.
    • Free dynamically allocated memory when done working with it.
    • Read How to debug small programs.
    • Grab a book.