You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

C语言哈希表实现问题:节点初始化与显示等报错咨询

C语言哈希表实现问题解答

问题1:create_table中赋值NULL的类型错误

原因

你定义的hashtable结构体中table是node_t*类型,意味着ht->table[i]是一个具体的node_t结构体实例,而非指针。NULL是指针常量,无法直接赋值给结构体类型,这就是编译错误的根源。

哈希表的每个槽应该是链表的头指针(node_t*),因此table的类型需要是node_t**(指针数组,每个元素指向对应槽的链表头)。

修正方案

  1. 修改hashtable结构体定义:
typedef struct hash_table{
  node_t **table; // 改为二级指针,指向存储链表头指针的数组
}hashtable;
  1. 调整create_table函数的内存分配与初始化逻辑:
hashtable *create_table(void){
  int i = 0;
  hashtable *ht = malloc(sizeof(hashtable));
  // 分配指针数组内存,每个元素对应一个槽的链表头指针
  ht->table = malloc(sizeof(node_t*) * SIZE);
  
  for(; i < SIZE; ++i){
    ht->table[i] = NULL; // 现在每个槽是指针类型,可直接赋值为NULL
  }
  
  return ht;
}

问题2:display_hashtable中类型不匹配的比较错误

原因

同样因table类型错误,ht->table[i]是node_t结构体实例,与NULL(指针)比较属于类型不匹配。此外,原显示逻辑错误:哈希表的每个槽是链表头,需遍历槽内的整个链表,而非直接访问ht->table[i].element(空指针访问会触发崩溃)。

修正方案

修改display_hashtable函数:

void display_hashtable(hashtable *ht){
  int i = 0;
  for(i = 0; i < SIZE; i++){
    node_t *current = ht->table[i];
    if(current == NULL){
      continue; // 当前槽为空,跳过
    }
    // 遍历当前槽的整个链表
    while(current != NULL){
      printf("Element: %s || Slot: %d || Key: %d.\n", 
             current->element, hash(current->key), current->key);
      current = current->next;
    }
  }
}

附加疑问:结构体调整是否正确?

你最初用数组node_t table[SIZE]时,无法赋值是因为数组是不可修改的左值,不能通过=直接赋值。改成node_t *table的方向是对的,但不够准确——正确类型应为node_t** table,因为我们需要存储的是链表头指针数组,而非结构体实例数组。

此外,需同步修改其他函数中对table的访问逻辑:

  • insert函数中获取槽的代码:
// 原代码:node_t **sentinel = &ht->table[hash(key)].next;
// 修改为:
node_t **sentinel = &ht->table[hash(key)];
  • find函数中初始化sentinel的代码:
node_t **sentinel = &ht->table[hash(key)];
  • delete函数中初始化sentinel的代码:
node_t **sentinel = &ht->table[hash(key)];

最后,建议添加哈希表内存释放函数避免泄漏:

void free_hashtable(hashtable *ht){
  for(int i=0; i<SIZE; i++){
    node_t *current = ht->table[i];
    while(current != NULL){
      node_t *tmp = current;
      current = current->next;
      free(tmp);
    }
  }
  free(ht->table);
  free(ht);
}
// 在main函数末尾调用:free_hashtable(ht);

内容的提问来源于stack exchange,提问作者Pit

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.06 09:55:25