GLib哈希表循环问题

2024-01-03

我要使用GLib http://en.wikipedia.org/wiki/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));

use

  a = g_malloc(sizeof *a);

通过这种方式,您可以“锁定”依赖关系,以便始终分配足够的空间来存储任何内容a点,即使您稍后更改类型。

此外,你应该仔细检查你所做的每一个演员。将任何非常量指针转换为gpointer是一个犹豫不决的程序员的标志。凭借油嘴滑舌,gpointer只是一个同义词void *,这样就不需要演员阵容了。它只会给你的代码增加麻烦,使其更难以阅读。

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

GLib哈希表循环问题 的相关文章

随机推荐