Search code examples
chashtablepass-by-referencepass-by-value

Setting Pointer References


I have a rehash function for a hash table like so:

int hash_rehash(hash_table *ht) {
    list *l = hash_list(ht); // creates a linked list of hash table members
    hash_table *nht = hash_createTable(ht->buckets * 2, ht->maxLoad, ht->hash); // new hash table with 2x the buckets
    unsigned int i = 0;
    list_node *c = l->head;
    hash_destroyTable(ht); // destroy the old hash table
    for (; i < l->size; i++, c = c->next) {
        hash_insert(nht, c->data); // loop through linked list to re-insert old hash table members
    }
    *ht = *nht; // reference of old hash table = reference of new hash table?
    list_destroyList(l);
    return 0;
}

However if I destroy the old hash table I run into a SIGABRT error when reading out all the members of the new table because nht is using the same memory I allocated for ht. What's the correct way to change the old hash table ht to reference the new hash table nht?


Solution

  • Accept a hash_table ** instead of a hash_table *. Then if your caller has a hash_table *ht, they will call hash_rehash(&ht), allowing the function to modify ht.