【问题标题】:Glib hash table storing incorrect keys存储错误键的 Glib 哈希表
【发布时间】:2011-10-19 09:53:05
【问题描述】:

我是第一次使用 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。有什么想法我在这里做错了吗?

【问题讨论】:

    标签: c glib


    【解决方案1】:

    取消引用dump_pair() 中的键指针怎么样?

    g_print ("Key: %u Value: %s\n", *key, value);
    

    【讨论】:

      【解决方案2】:

      num_id 变量在插入调用中复制时是否应该获取其地址?

      g_memdup(num_id, sizeof(num_id))
      

      应该是

      g_memdup(&num_id, sizeof(num_id))
      

      由于您没有显示num_id 的类型,因此有点难以确定,但是由于该参数对应于存储在表中的值,因此它应该是一个指针。

      将您的键和值收集到单个 struct 中并插入它们会更有意义。

      【讨论】:

      • 对不起,num_id是指针,表的值是正确的。只有键是错的。
      【解决方案3】:

      您使用 uint32_t 作为密钥,但您使用 64 位密钥声明了 g_hash_table_new(g_int64_hash, g_int64_equal)。为什么不重新声明为g_hash_table_new(g_int32_hash, g_int32_equal)

      如果您仍想按原样使用它,则需要在复制新值之前将密钥的所有 64 位清零。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多