Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>It doesn't make sense to allocate all 101 (or however many) buckets upfront, you'd typically allocate them one at a time, when inserting new data into the table.</p> <p>It <em>does</em> make sense to pre-allocate the hash array, which will have a fixed size, but that is an <em>array of bucket pointers</em>, not an array of buckets, so some of the answers are wrong.</p> <p>You'd have something like this, to create a an empty hash table, with a fixed-size bucket array:</p> <pre><code>hash_table * hash_table_new(size_t capacity) { size_t i; hash_table *t = malloc(sizeof *t); t-&gt;size = capacity; t-&gt;bucket = malloc(t-&gt;size * sizeof *t-&gt;bucket); for(i = 0; i &lt; t-&gt;size; i++) t-&gt;bucket[i] = NULL; return t; } </code></pre> <p>This code:</p> <ul> <li>Allocates a hash_table structure to hold the table</li> <li>Initializes it's size with indicated capacity</li> <li>Allocates an array of bucket pointers of the proper length</li> <li>Makes sure each bucket pointer is NULL (which cannot properly be done with memset(), as it's not safe to assume that "all bits zero" is the way NULL looks in memory)</li> <li>Uses <code>sizeof</code> whenever possible, but not on types, so no parenthesis</li> <li>Doesn't cast the return value of <code>malloc()</code>, since that is never a good idea in C</li> <li>Doesn't check the return value of malloc(), of course you should do that in real code</li> </ul> <p>A second function would be needed to do an actual hash insert, which will then need to allocate a new bucket, compute the hash value from the key, pick the proper location in the hash table's array, and insert the new entry there.</p>
 

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