我第一次使用glib并且在使用哈希表时遇到了一些麻烦。我正在尝试使用uint32_t作为密钥。
GHashTable *fwd_table = g_hash_table_new(g_int64_hash, g_int64_equal);
// some code here
while(something is true) {
uint32_t net_addr = ip_strtoint(addr) - net_mask(addr); // value of the key
printf("The net_addr is %u\n",net_addr);
g_hash_table_insert(fwd_table, g_memdup(&net_addr, sizeof(net_addr)),
g_memdup(num_id, sizeof(num_id)));
}
void dump_pair (const uint32_t *key, const char *value) {
g_print ("Key: %u Value: %s\n", key, value);
}
g_hash_table_foreach (fwd_table, (GHFunc)dump_pair, NULL);
输出结果为:
The net_addr is 3232301056
The net_addr is 3232251904
The net_addr is 3232284672
The net_addr is 3232251686
The net_addr is 3372220416
Key: 6307440 Value: 1
Key: 6307536 Value: 2
Key: 6307728 Value: 5
Key: 6307344 Value: 3
Key: 6307632 Value: 7
密钥应与net_addr对应。我在这里做错了什么想法?
答案 0 :(得分:1)
取消引用dump_pair()
中的键指针怎么样?
g_print ("Key: %u Value: %s\n", *key, value);
答案 1 :(得分:0)
当你在插入调用中复制它时,num_id
变量是否应该具有地址?
即
g_memdup(num_id, sizeof(num_id))
应该是
g_memdup(&num_id, sizeof(num_id))
由于您没有显示num_id
的类型,因此有点难以确定,但由于该参数对应于存储在表中的值,因此它应该是指针。
将您的密钥和值收集到一个struct
中会更有意义,并插入它们。
答案 2 :(得分:0)
您正在使用uint32_t
作为密钥,但您使用64位密钥声明了g_hash_table_new(g_int64_hash, g_int64_equal)
。为什么不将其重新声明为g_hash_table_new(g_int32_hash, g_int32_equal)
。
如果您仍然希望按原样使用它,则需要将所有64位密钥清零,然后再复制其中的新值。