【问题标题】:c pointer to pointer how to iterate through itc指针指向如何遍历它
【发布时间】:2015-08-12 01:00:40
【问题描述】:
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 链接到第一个位置。

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

【问题讨论】:

  • 我不会完全这样做,但类似。也就是说,我一看就觉得没问题。哦,在 C 中你真的应该使用 NULL 作为空指针。
  • 你是认真的吗?因为我不知道自己在做什么......
  • 添加到我之前的评论中,一目了然如果所有指针都正确分配或以其他方式初始化。 :) 至于指针的问题,看成指针数组就好了。
  • 挑剔:array of pointers to hashLinks --> pointer to pointer to hashLinks
  • while(current-&gt;next !=0) -->> while(current != NULL)

标签: c pointers struct pointer-to-pointer


【解决方案1】:

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

您通过链接的迭代很好并且正确frees 表中的所有hashLinks。但是,请考虑迭代后ht 的状态。您根本不会更改 ht-&gt;table[i] 的值,因此在您离开循环后,指针仍将存储在表中。如果要重用该表,则应在不再需要时将指针设置为 0,即在 current = ht-&gt;table[i]; 之后的某处添加 ht-&gt;table[i] = 0

如果这个方法是表的“析构函数”的一部分(即,像hashmap_delete(...)这样的一些方法),那么你可以在完成迭代后简单地free hashmap,即在后面添加free(ht); for-loop。

【讨论】:

    【解决方案2】:

    简化:

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

    可以进一步简化为只有一个循环,但这留给读者作为练习......


    注意:作为副作用,这会将 ht->table[] 中的所有指针设置为 NULL;这很好,因为在释放链接列表之后,它们无论如何都变得陈旧了。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-05-29
      • 1970-01-01
      • 2021-11-23
      • 2013-03-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多