C Glib哈希表替换

C Glib哈希表替换,c,hashtable,glib,C,Hashtable,Glib,我正在使用GLib哈希表。我试图获取我找到的键的当前值,然后增加它的值。我不太确定如何替换现有值 typedef struct { gchar *key; guint my_int; } my_struct; char *v; v = g_hash_table_lookup(table, my_struct.key); if (v == NULL) g_hash_table_insert(table, g_strdup(my_struct.key), (gpointer

我正在使用GLib哈希表。我试图获取我找到的键的当前值,然后增加它的值。我不太确定如何替换现有值

 typedef struct {
   gchar *key;
   guint my_int;
 } my_struct;

char *v;
v = g_hash_table_lookup(table, my_struct.key);
if (v == NULL) 
   g_hash_table_insert(table, g_strdup(my_struct.key), (gpointer)(my_struct.my_int));
else 
   g_hash_table_replace() // here I'd like to do something like current_val+1
任何想法都将不胜感激。

您看过 它似乎采用与insert相同的参数。
查找调用将返回一个gpointer。您需要将结果强制转换为guint、increment,然后调用replace来替换递增的值

g_hash_table_replace(table, my_struct.key, v + 1)
但是,为了匹配您的结构,v应该是
guint
,而不是
char*

但是请注意,您正在进行的转换不是一个好主意,因为整数不能保证适合指针。最好采取以下措施:

 typedef struct {
   gchar *key;
   guint *my_int;
 } my_struct;

guint *v;
v = (guint*) g_hash_table_lookup(table, my_struct.key);
if (v == NULL) 
{
   my_struct.my_int = g_malloc(sizeof(guint));
   *(my_struct.my_int) = 0;
   g_hash_table_insert(table, my_struct.key, my_struct.my_int);
}
else 
{
   (*v)++;
   g_hash_table_replace(table, my_struct.key, v) // here I'd like to do something like current_val+1
}

是的,但我不太确定如何从g_hash_table_lookup检索键中获取当前值。我们并不是在DOS及其怪异内存模型的糟糕年代。指针可以在我所知道的每一个当前系统上保存系统字大小的整数,这对于很多情况来说已经足够好了。(现在,不再安全的是假设所有指针都适合整数。“全世界都是Vax”不再成立。)