【问题标题】:Setting Pointer References设置指针引用
【发布时间】:2015-02-24 04:44:17
【问题描述】:

我有一个哈希表的 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 以引用新哈希表 nht 的正确方法是什么?

【问题讨论】:

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


    【解决方案1】:

    接受hash_table ** 而不是hash_table *。然后如果你的调用者有hash_table *ht,他们会调用hash_rehash(&amp;ht),允许函数修改ht。

    【讨论】:

    • 是否每个调用 hash_rehash 的函数也必须接受 hash_table **?
    • @user2506293 取决于它是如何使用它的,但很可能是的。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-05-29
    • 2013-08-21
    • 2021-11-14
    • 2012-10-16
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多