C 存储错误密钥的Glib哈希表

C 存储错误密钥的Glib哈希表,c,glib,C,Glib,我是第一次使用glib,但在使用哈希表时遇到了一些问题。我试着用uint32作为钥匙 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(

我是第一次使用glib,但在使用哈希表时遇到了一些问题。我试着用uint32作为钥匙

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

键应与网络地址相对应。你知道我做错了什么吗?

在insert调用中复制
num\u id
变量时,它的地址是否应该被取下来

应该是

g_memdup(&num_id, sizeof(num_id))
由于没有显示
num\u id
的类型,因此有点难以确定,但由于该参数对应于表中存储的值,因此它应该是一个指针


将密钥和值收集到单个
结构中并插入它们会更有意义。

转储对()中取消对密钥指针的引用怎么样


您正在使用
uint32\u t
作为键,但您声明了带有64位键的
g\u hash\u table\u new(g\u int64\u hash,g\u int64\u equal)
。为什么不重新声明它为
g\u hash\u table\u new(g\u int32\u hash,g\u int32\u equal)


如果仍要按原样使用,则需要先将键的所有64位置零,然后再复制其中的新值。

对不起,num_id是指针,表中的值是正确的。只有钥匙错了。
g_memdup(&num_id, sizeof(num_id))
g_print ("Key: %u Value: %s\n", *key, value);