【发布时间】:2016-03-18 06:13:19
【问题描述】:
在以下算法中获取一些段错误以将元素添加到哈希表中的正确存储桶。
我的结构是基本的:
struct kv {
char* key;
unsigned val;
struct kv* next;
};
struct hashtable {
struct kv** table;
unsigned size;
};
还有我的越野车功能:
struct kv* ht_find_or_put(char* word, unsigned value,
struct hashtablet* hashtable,
unsigned (*hash)(char*))
{
unsigned index = hash(word) % hashtable->size;
struct kv* ke = malloc(sizeof (struct kv));
for (ke = hashtable->table[index]; ke != NULL; ke = ke->next)
{
if (strcmp(ke->key, word) == 0)
return ke;
}
if (ke == NULL)
{
ke->key = word;
ke->val = value;
ke->next = hashtable->table[index];
hashtable->table[index] = ke;
}
return ke;
}
我知道我还没有添加所有测试(如果 malloc 失败等)只是试图调试这个特定问题......
我正在这样分配我的表:
struct hashtable* hashtable_malloc(unsigned size)
{
struct hashtable *new_ht = malloc(sizeof(struct hashtable));
new_ht->size = size;
new_ht->table = malloc(sizeof(struct kv) * size);
for(unsigned i = 0; i < size; i++)
new_ht->table[i] = NULL;
return new_ht;
}
我们将不胜感激任何形式的帮助。我才刚刚开始学习。
【问题讨论】:
-
你能标出发生段错误的行吗?你试过调试器吗?创建一个Minimal, Complete, and Verifiable Example 也是一个好主意。