我将使用 GLib在 C 程序中的哈希表实现,只是现在 我只是在试验它。我写了下面一段代码用于测试:
#include <glib.h>
#include <stdlib.h>
#include <stdint.h>
#include <stdio.h>
#include <string.h>
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;
}
我的测试代码以某种方式正确迭代,但在循环中它总是返回最后一个键和最后一个值对,而且它总是相同的。这里有什么问题?上面的代码可能无法以其原样格式运行。我只是复制并粘贴了一些部分,以便清楚地了解我正在尝试做什么。
最佳答案
我认为您的插入代码已损坏。您只分配一次内存,但随后进行多次插入,增加存储在每次插入之间的单个分配位置中的值。
哈希表存储你的指针,所以它最终会将每个键与同一个指针相关联。
此外,为了保持一致性,您可能应该将 g_malloc()
与 glib 一起使用。
而且我总是建议对对象而不是它们的类型使用sizeof
;这样你就不会以同样危险的方式重复自己。所以,而不是
guint32 *a;
a = g_malloc(sizeof (guint32));
使用
a = g_malloc(sizeof *a);
这样您就可以“锁定”依赖关系,这样您就可以始终分配足够的空间来存储 a
指向的任何内容,即使您稍后更改类型也是如此。
此外,你应该仔细检查你所做的每一个 Actor 。将任何非常量指针转换为 gpointer
是犹豫不决的程序员的标志。对于 glib,gpointer
只是 void *
的同义词,因此永远不需要转换。它只会给您的代码增加麻烦,使其更难阅读。
关于c - GLib 哈希表循环问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/700485/