我想用uthash创建一个哈希图。
我希望键和值是一个结构,包含一个字符串和一个 size_t,如下所示:
typedef struct hash_ptr {
char* string;
size_t len;
}hash_ptr;
哈希表本身如下所示:
typedef struct hash_map_entry {
struct hash_ptr *key;
struct hash_ptr *value;
UT_hash_handle hh;
}hash_map_entry;
为了向地图中添加新条目,我编写了一个名为 add_entry() 的新函数:
void add_entry(hash_map_entry *map, hash_ptr *key, hash_ptr *value) {
hash_map_entry *entry;
HASH_FIND(hh, map, key, sizeof *key, entry);
if (entry == NULL) {
entry = (hash_map_entry*) malloc(sizeof *entry);
memset(entry, 0, sizeof *entry);
entry->value = value;
entry->key = key;
HASH_ADD(hh, map, key, sizeof *key, entry);
}
}
但是,在初始化并调用 add_entry()...
hash_map_entry *map = NULL;
hash_ptr *key = (hash_ptr*) malloc(sizeof *key);
memset(key, 0, sizeof *key);
key->string = "Is this the Krusty Krab?";
key->len = strlen(key->string);
hash_ptr *value = (hash_ptr*) malloc(sizeof *value);
memset(value, 0, sizeof *value);
value->string = "No, this is Patrick!";
value->len = strlen(value->string);
add_entry(map, key, value);
...HASH_FIND 没有找到添加的条目:
hash_map_entry *find_me;
HASH_FIND(hh, map, key, sizeof *key, find_me);
find_me 为 NULL。
我按照官方用户指南中使用结构作为密钥的说明进行操作。
我哪里错了?