Reputation:
I have some code in C where i want to use int as key and as values in gnome hash tables. But if i write:
GHashTable* table = g_hash_table_new(g_direct_hash, g_direct_equal);
int tmp = 0;
int value = 255;
g_hash_table_insert(table, (gpointer)tmp, (gpointer) 255);
I get some warning about casting pointer from integer of different size and the application return segmentation fault. I know this can be done via pointer, but I wanted to know if there was a way to optimize the procedure using directly int. I'm also opened to try new solution (always in C with gnome hash tables) that performs better. I simply have to create an hash table and fill it with the same value for a certain amount of keys, then at a latter stage make some comparison with values within it and lastly make a comparison for every value inside it with a fixed value.
Upvotes: 4
Views: 5334
Reputation: 5733
You have two options:
g_direct_hash()
with GINT_TO_POINTER()
keys; org_int_hash()
with pointers to your integer keys.So in the first case, that would be:
int tmp = 0;
int value = 255;
GHashTable *table = g_hash_table_new_full (g_direct_hash, g_direct_equal, NULL, NULL);
g_hash_table_insert (table, GINT_TO_POINTER (tmp), GINT_TO_POINTER (value));
In the second, it’s:
int tmp = 0;
int value = 255;
GHashTable *table = g_hash_table_new_full (g_int_hash, g_int_equal, NULL, NULL);
g_hash_table_insert(table, &tmp, GINT_TO_POINTER (value));
Though you must guarantee that the key pointed to by &tmp
doesn’t change while its entry is in the hash table — so this only works with allocated keys, like this:
int tmp = 0;
int *key = g_new0 (gint, 1);
*key = tmp;
int value = 255;
GHashTable *table = g_hash_table_new_full (g_int_hash, g_int_equal, g_free, NULL);
g_hash_table_insert(table, key, GINT_TO_POINTER (value));
So the second option makes more sense if, for example, you want to key a hash table based off the value of an integer field in an existing heap-allocated structure which will be stored as the value in the hash table entry (so you don’t require an extra allocation just for the key).
Note that in both cases, you use GINT_TO_POINTER()
on the value to be stored, as values are always treated as pointers, and are independent of the hash and equality functions you’re using.
Note also that using g_hash_table_new_full()
and passing NULL
for the final two arguments (apart from in the third example) makes it clearer that the hash table does not take ownership of the keys and values you pass it. (The final two arguments give the free functions for keys and values.)
Upvotes: 7
Reputation: 21837
You should use GINT_TO_POINTER macro:
g_hash_table_insert(table, GINT_TO_POINTER(tmp), GINT_TO_POINTER(255));
That will allow to get rid from warning: cast to pointer from integer of different size
warning.
Upvotes: 3