Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>Personally I am not a huge fan of using typedefs, especially when you are a beginner. I think that may be partially what is confusing you. You are better avoiding things like: </p> <pre><code>typedef struct hashtable * HashTablePtr; </code></pre> <p>Using to many typedefs will make your code harder to read since you will need to constantly look up what they are referring too. </p> <p>The main problem is that you were allocating the memory for the size of a hashtable/list pointer and not for the size of their respected structures. I think the code below shows this well. You will also want to check if you allocations worked. If malloc, calloc, realloc. etc. fail they return NULL. If this happens and you do not check for this case you will get a segfault error and your program will crash. </p> <p>Also follow the c99 standard, and put all of your variable declarations at the start of the function.</p> <p><a href="http://www.open-std.org/JTC1/SC22/wg14/www/docs/n1124.pdf" rel="nofollow noreferrer">c99 std</a></p> <p><a href="http://www.poplog.org/docs/popdocs/pop11/unix/malloc" rel="nofollow noreferrer">malloc manpage</a></p> <pre><code>struct hashtable * createHashTable(unsigned int capacity){ struct hashtable *hash; struct list *mylist; /* You want to allocate size of the hash structure not the size of a pointer. */ hash = malloc(sizeof(struct hashtable)); // always make sure if the allocation worked. if(hash == NULL){ fprintf(stderr, "Could not allocate hashtable\n"); return NULL; } hash-&gt;size = 0; hash-&gt;capacity = capacity; /* Unless you need the memory to be zero'd I would just use malloc here * mylist = calloc(capacity, sizeof(struct list)); */ mylist = malloc(capacity * sizeof(struct list)); if(mylist == NULL){ fprintf(stderr, "Could not allocate list\n"); free(hash); /* free our memory and handle the error*/ return NULL; } mylist-&gt;head = NULL; mylist-&gt;size = 0; mylist-&gt;tail = NULL; hash-&gt;list = mylist; return hash; } </code></pre> <p>Also remember to free you list before you free your hashtable:</p> <pre><code>free(myhash-&gt;list); free(myhash); </code></pre>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. VO
      singulars
      1. This table or related slice is empty.
    2. VO
      singulars
      1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload