tags:

views:

60

answers:

2

I'm using GLib Hash Table. I'm trying to get the current value of the key that I found and then increment its value. I'm not quite sure how can I replace the existing value.

 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

Any ideas will be appreciate it.

+1  A: 
SB
I did, but I'm not quite sure how to get the current value from the g_hash_table_lookup retrieved key.
Robert
A: 
g_hash_table_replace(table, my_struct.key, v + 1)

However, to match your struct, v should be a guint, not a char * .

But note that the casting you're doing is not a good idea, as integers are not guaranteed to fit in pointers. It would be better to do something like:

 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
}
Matthew Flaschen
We're not in the bad old days of DOS and its weird memory models. Pointers can hold integers of the size of the system word on every current system I'm aware of, which is good enough for a lot. (Now, what's not safe any more is to assume that all pointers fit in an int. "All the world's a Vax" no longer holds true.)
Donal Fellows