首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >指向指针的C指针如何遍历它

指向指针的C指针如何遍历它
EN

Stack Overflow用户
提问于 2015-05-29 16:33:07
回答 2查看 1.1K关注 0票数 0
代码语言:javascript
复制
struct hashLink

{
   KeyType key; /*the key is what you use to look up a hashLink*/
   ValueType value; /*the value stored with the hashLink, an int in our case*/
   struct hashLink *next; /*notice how these are like linked list nodes*/
};

struct hashMap
{
    hashLink ** table; /*array of pointers to hashLinks*/
    int tableSize; /*number of buckets in the table*/
    int count; /*number of hashLinks in the table*/
};

我正在尝试用hashLinks遍历hashMap。这是正确的方法吗?hashLinks在数组中,且在链表中可以有更多hashLinks链接到它们。我只是不明白如何让指针指向指针。tableSize是数组中元素的数量。在每个数组位置,可能有更多的hashLinks链接到第一个位置。

代码语言:javascript
复制
for(int i = 0; i < ht->tableSize; i ++)
{
    hashLink *current;

    if (ht->table[i] != 0)
    {
        current = ht->table[i];

        while(current->next !=0)
        {
            hashLink *next;
            next = current->next;
            free(current->key);
            free(current);
            current = next;
        }

        free(current->key);
        free(current);
    }
    else 
    {
        continue;
    }

        counter++;
    }
}
EN

回答 2

Stack Overflow用户

发布于 2015-05-29 17:13:33

是的,这是可行的,但是你最终得到了一个包含悬空指针的哈希表。此外,正如Joachim所指出的,只要您假设结构中包含的值是合理的,即tableSize包含table中的条目数量,并且hashLink已经正确分配,它就可以工作。

你通过链接的迭代是好的,并且正确地free了表中的所有hashLink。但是,考虑一下迭代之后ht的状态。您根本不会更改ht->table[i]的值,因此在您离开循环之后,指针仍将存储在表中。如果你想重用这个表,当你不再需要它们的时候,你应该将指针设置为0,例如,在current = ht->table[i];之后的某个地方添加ht->table[i] = 0

如果此方法是表的“析构函数”的一部分(例如,像hashmap_delete(...)这样的方法),那么您可以在完成迭代后简单地free哈希图,即在for-loop之后添加free(ht);

票数 0
EN

Stack Overflow用户

发布于 2015-05-29 17:28:37

简化版:

代码语言:javascript
复制
for(int i=0; i < ht->tableSize; i++)
{
    hashLink *current;

    while (ht->table[i] != NULL) {
        current = ht->table[i];
        ht->table[i] = current->next;

        free(current->key);
        free(current);
    }
}

它可以进一步简化为 one loop,但这将作为练习留给读者...

注意:作为一个副作用,这会将ht->table[]中的所有指针设置为NULL;这很好,因为在释放链表之后,它们已经变得陈旧。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/30524869

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档