【发布时间】:2019-05-10 03:55:45
【问题描述】:
我是一名学习数据结构的学生,试图实现一个 hashmap 函数,该函数将使用链表的节点添加元素。当我调用下一个值时,我最终在我的 else 语句中得到一个段错误,我不知道为什么。任何帮助表示赞赏,谢谢大家。
void insertMap (struct hashMap * ht, KeyType k, ValueType v)
{ /*write this*/
int idx = stringHash1(k);
struct hashLink * hlnk;
struct hashLink * plink;
assert(ht);
if(ht->table[idx] == NULL){
hlnk = (struct hashLink *) malloc(sizeof(struct hashLink));
hlnk->value = v;
hlnk->key = k;
hlnk->next = NULL;
ht->table[idx] = hlnk;
ht->count++;
}
else{
plink = ht->table[idx];
hlnk = (struct hashLink *) malloc(sizeof(struct hashLink));
hlnk->value = v;
hlnk->key = k;
hlnk->next = plink->next;
plink->next = hlnk;
ht->count++;
}
}
【问题讨论】:
-
放置整个代码总是有帮助的,或者如果不是数据结构和函数的相关定义。我们不知道你使用的 struct hashMap、struct hashLink 和类似的其他函数的定义。代码中的错误可能在任何地方。
-
检查您最初是否真的将事物设置为 NULL。如果您没有将所有可能的
ht->table[idx]entries 设置为 NULL,那么当您真的想进入 if 语句的第一部分时,您可能最终会进入else部分。
标签: c linked-list hashmap