GLib哈希表循环问题

我将在C程序中使用GLib的Hash表实现,现在我只是在尝试它。 我编写了以下代码用于测试:

#include  #include  #include  #include  #include  int main(){ // Some codes and declerations here GHashTable *g_hash_table; uint32_t *a; a=(uint32_t *)malloc(sizeof(uint32_t)); if(a==NULL){ printf("Not Enough Mem For a\n"); return 1; } *a=1123231; uint32_t* key; key=(uint32_t *)malloc(sizeof(uint32_t)); if(key==NULL){ printf("Not Enough Mem For key\n"); return 1; } *key=122312312; int i; g_hash_table=g_hash_table_new(g_int_hash, g_int_equal); for(i=0;i<TABLE_SIZE;i++){ *key+=1; *a+=1; g_hash_table_insert(g_hash_table,(gpointer)key,(gpointer)a); uint32_t *x=(uint32_t *)g_hash_table_lookup(g_hash_table,key); printf("Counter:%d, %u\n",i,*x); } GHashTableIter iter; g_hash_table_iter_init(&iter,g_hash_table); int size=g_hash_table_size(g_hash_table); printf("First size: %d\n",size); uint32_t *val; uint32_t *key_; int counter=0; // My problem is in the following loop it // always returns the same and the last key value pair while(g_hash_table_iter_next(&iter,(gpointer*)(void*)&key_,(gpointer*)(void*)&val)){ counter++; printf("%u %u\n",(uint32_t)*key_,(uint32_t)*val); printf("Counter: %d\n",counter); } //Some more code here return 0; } 

不知怎的,我的测试代码正确迭代,但在循环中它总是返回最后一个键和最后一个值对,它总是相同的。 这里有什么问题? 上面的代码可能无法以其格式运行。 我只是复制并粘贴了一些部分,以便清楚地了解我要做的事情。

key ,声明中有错误。 您始终将相同的指针放在哈希表中。 尝试:

 #include  #include  #include  #include  #include  #define TABLE_SIZE 12 int main() { // Some codes and declarations here GHashTable *g_hash_table; int i; g_hash_table = g_hash_table_new(g_int_hash, g_int_equal); for (i=0; i %u\n", *key ,*x); } GHashTableIter iter; int size=g_hash_table_size(g_hash_table); printf("First size: %d\n", size); uint32_t *val; uint32_t *key_; // My problem is in the following loop // it always returns the same and the last key value pair g_hash_table_iter_init (&iter, g_hash_table); while (g_hash_table_iter_next (&iter, (gpointer) &key_, (gpointer) &val)) { printf("key %u ---> %u\n", (uint32_t)*key_, (uint32_t)*val); } // TODO: free keys return 0; } 

我认为您的插入代码已损坏。 你只需要分配一次内存,然后进行多次插入,增加存储在每个内存之间的单个分配位置的值。

哈希表存储您的指针,因此它最终会将每个键与相同的指针相关联。

此外,为了保持一致性,您可能应该将g_malloc()与glib一起使用。

而且我总是建议在对象上使用sizeof而不是在它们的类型上; 这样你就不会以一种危险的方式重复自己。 所以,而不是

  guint32 *a; a = g_malloc(sizeof (guint32)); 

使用

  a = g_malloc(sizeof *a); 

通过这种方式,您可以“锁定”依赖关系,这样您就可以随时分配足够的空间来存储任何点,即使您稍后更改了类型。

此外,你应该仔细看看你做的每一个演员。 将任何非常量指针gpointergpointer是一个犹豫不决的程序员的标志。 使用glib, gpointer只是void *的同义词,因此永远不需要强制转换。 它只会增加你的代码,使其更难阅读。