我将在C程序中使用GLib的Hash表实现,现在我只是在尝试它.我编写了以下代码用于测试:
#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;
}
Run Code Online (Sandbox Code Playgroud)
不知何故,我的测试代码正确迭代,但在循环中它总是返回最后一个键和最后一个值对,它总是相同的.这里有什么问题?上面的代码可能无法以格式运行.我只是复制并粘贴了一些部分,以便清楚地了解我要做的事情.
我认为您的插入代码已损坏.您只需分配一次内存,然后执行多次插入,增加存储在每个内存之间的单个分配位置的值.
哈希表存储您的指针,因此它最终会将每个键与相同的指针相关联.
此外,您应该使用g_malloc()glib,以保持一致性.
而且我总是建议使用sizeof对象而不是它们的类型; 这样你就不会以一种危险的方式重复自己.所以,而不是
guint32 *a;
a = g_malloc(sizeof (guint32));
Run Code Online (Sandbox Code Playgroud)
使用
a = g_malloc(sizeof *a);
Run Code Online (Sandbox Code Playgroud)
通过这种方式,您可以"锁定"依赖关系,这样您就可以随时分配足够的空间来存储任何a点,即使您稍后更改了类型.
此外,你应该仔细看看你做的每一个演员.将任何非常量指针强制转换gpointer为犹豫不决的程序员的标志.使用glib,gpointer它只是一个同义词void *,因此永远不需要强制转换.它只会增加你的代码,使其更难阅读.