【发布时间】:2021-11-19 02:41:42
【问题描述】:
我正在尝试创建一个函数,它将输入应用于哈希表中的所有条目。此处显示的示例用于在哈希表的所有区域上输入相同的值。前几天我让它工作了,但现在它似乎总是失败(不知道发生了什么变化)并且我的 github 历史中的版本都有相同的问题。使用 gdb 进行调试时,我可以看到在我的测试中应用程序没有出现,并且所有条目都保持为 NULL。谁能看到我的代码有什么问题?
正在测试的函数:
void hash_table_apply_to_all(hash_table_t *ht, apply_function apply_fun, void *arg)
{
for (int i = 0; i < No_Buckets; i++)
{
entry_t *current_entry = (&ht->buckets[i])->next;
while (current_entry != NULL)
{
apply_fun(current_entry->key, ¤t_entry->value, arg);
current_entry = current_entry->next;
}
}
}
应用值插入函数:
void value_insert(int key_ignored, char **value, void *x)
{
*value = (char *) x;
}
单元测试(CUnit):
void test_apply_to_all()
{
hash_table_t *ht = hash_table_create();
char *valtest = "a";
bool result = NULL;
hash_table_apply_to_all(ht, value_insert, valtest); // here I am trying to apply the value "a" to all entries
for (int i = 0; i < No_Buckets; i++)
{
hash_table_lookup(ht, i, &result);
if (!result)
{
break;
}
}
CU_ASSERT_TRUE(result);
hash_table_destroy(ht);
}
结构
struct entry
{
int key; // holds the key
char *value; // holds the value
entry_t *next; // points to the next entry (possibly NULL)
};
struct hash_table
{
entry_t buckets[No_Buckets];
};
apply函数的typedef:
typedef void(*ioopm_apply_function)(int key, char **value, void *extra);
查找函数
char *hash_table_lookup(ioopm_hash_table_t *ht, int key, bool *result)
{
entry_t *tmp = find_previous_entry_for_key(&ht->buckets[key % No_Buckets], key);
entry_t *next = tmp->next;
if (tmp && tmp->next != NULL)
{
next = tmp->next;
}
if (next && next->value)
{
*result = true;
return (next->value);
}
else
{
*result = false;
return (NULL);
}
}
【问题讨论】:
-
如何创建 hash_table ht ?你能显示代码吗?
-
@PtitXav
hash_table_t *hash_table_create() { hash_table_t *result = calloc(1, sizeof(hash_table_t)); return result; } -
你创建了一个哈希表,所有内存都设置为 0 :下一个是 NULL :你永远不会在下一个上附加任何东西。
-
@Ptit Xav 如何在我的函数中解决这个问题?
-
看起来您正在向空哈希表上的所有应用程序?也许用条目填充它?
标签: c unit-testing hashtable void-pointers