Reputation: 13
I'm dealing with large numbers coming from the hash table. I'm wondering what would be a good way of adding them to a constant (100) taking into account portability. Glib's documentation highlights that using GINT_TO_POINTER is not portable in any way. Any ideas would be appreciated!
gpointer v, old_key;
gint value; // ?
if(g_hash_table_lookup_extended(table, key, &old_key, &v)){
value = GPOINTER_TO_INT(v); // ?
value = value + 100;
}
g_hash_table_replace(table, g_strdup(key), GINT_TO_POINTER(value)); // ?
Upvotes: 1
Views: 2438
Reputation: 284816
Rather than storing an integer inside a pointer, have the pointer point to an integer:
gpointer v, old_key;
int *int_v;
if(g_hash_table_lookup_extended(table, key, &old_key, &v)){
int_v = (int *)v;
int new_value = *int_v + 100;
int_v = g_malloc(sizeof(int));
*int_v = new_value;
}
g_hash_table_replace(table, g_strdup(key), int_v);
For a new value, use g_malloc
:
// ...
int *value = g_malloc(sizeof(int));
// ...
g_hash_table_insert(table, key, value);
To ensure keys and values are destroyed properly, pass destructor functions like g_free
to g_hash_table_new_full
.
Upvotes: 1
Reputation: 5938
I am not familiar with gnome library, but from GNOME Documentation Library:
YOU MAY NOT STORE POINTERS IN INTEGERS. THIS IS NOT PORTABLE IN ANY WAY SHAPE OR FORM. These macros ONLY allow storing integers in pointers, and only preserve 32 bits of the integer; values outside the range of a 32-bit integer will be mangled.
The only thing not portable is to store pointers in integers. If you just:
It shall be okay.
Upvotes: 5