c++ - 为什么哈希表中的第 2 级指针不需要 malloc() 来分配内存?

标签 c++ c pointers memory-management hash

我目前正在学习分离链来解决散列中的冲突。下面显示了一个创建哈希表的示例。我看到 hash_tbl *new_table = malloc(sizeof(hash_tbl));new_table 分配一大块内存.接下来,new_table->list = malloc(sizeof(node *) * size); 似乎将 new_table 除以size存储 node **list 的第一级指针.

Q1:我不明白的是为什么我不需要 malloc() node **list; 指针的第二级标记为###?

Q2:由于代码是正确的,for (int i=0; i<size; i++){ new_table->list[i] = NULL; }初始化new_tbl->list[i]指向的链表的头指针?

附注谁能用图形说明他的解释?

typedef struct Node {
    char *str;
    struct Node *next;
} node;

typedef struct Hash_Tbl {
    int size;       
    node **list; //### 
} hash_tbl;

int main() {
  int size = 6;
  create_hash_table(size);
}
hash_tbl *create_hash_table(int size) {
  if (size < 1)   return NULL;

  hash_tbl *new_table = malloc(sizeof(hash_tbl));
  if (new_table == NULL)    return NULL;

  new_table->list = malloc(sizeof(node *) * size);
  if (new_table->list == NULL)     return NULL;

  // Initialize the elements of the hash table
  for (int i=0; i<size; i++){
    new_table->list[i] = NULL;
  }

  new_table->size = size;

  return new_table;
}

最佳答案

I can't figure out is that why do I NOT need to malloc() the 2nd level of the pointer at node **list;

由于哈希表一开始是空的,因此您不需要分配第 2 级。 create_hash_table 的代码将所有桶设置为 NULL 以指示它们为空。

does [for loop] initialize the head pointer of the linked list pointed to be new_tbl->list[i]?

哈希表中没有一个“头指针”。 list[] 数组的每个元素都是它自己的头指针。所有这些指针都被初始化为NULL,表示它们对应的桶是空的。

最初,所有的遗愿 list 都是空的。当您开始向哈希表中添加项目时,列表就会开始填充。

下图显示了一个包含六个桶的哈希表。桶 1 和 3 有一些元素;剩下的桶是空的。桶 1 没有碰撞,而桶 3 有双向碰撞。

Memory layout

关于c++ - 为什么哈希表中的第 2 级指针不需要 malloc() 来分配内存?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33138313/

相关文章:

C++ 快速排序实现,没有正确的输出

python - 如何从 C++ 执行 python

c++ - *.cpp 文件中的 Typedef 模板类指针

c - 为什么不保存在双指针内部?

c - 为什么 char* 数据类型的大小对应于计算机的字大小(4 字节或 8 字节),而 char 仅获取 1 字节?

c - 函数指针分配在堆上

c++ - 高效稳定的有序数之和

c - TI-84 : call a function from the catalog with z88dk

c - 在 C99 的嵌套 for 循环中声明计数器变量的最佳实践

C++ 为什么我应该抑制默认的复制构造函数?