设置指针引用

时间:2014-12-27 04:47:19

标签: c hashtable pass-by-reference pass-by-value

我有一个哈希表的rehash函数,如下所示:

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;
}

但是,如果我销毁旧的哈希表,我会在读出新表的所有成员时遇到SIGABRT错误,因为nht正在使用我为ht分配的相同内存。更改旧哈希表ht以引用新哈希表的正确方法是什么?

1 个答案:

答案 0 :(得分:1)

接受hash_table **而不是hash_table *。然后,如果您的来电者有hash_table *ht,他们会拨打hash_rehash(&ht),允许该功能修改ht