Reputation: 361
Hello I was wondering if it was possible to store a float as key into a GhashTable considering there is no GFLOAT_TO_POINTER macro methdod.
I am following a tutorial I found online by IBM http://www.ibm.com/developerworks/linux/tutorials/l-glib/section5.html , but I can't seem to find a way to use an float as a key.
Any help would be great thanks!
typedef struct Settings settings;
typedef struct Preset preset;
struct Gnomeradio_Settings
{
GList *presets;
};
struct Preset
{
gchar *name;
gfloat freq;
};
I want to put all freq from settings.presets list as key in a GHashTable
GHashTable *hash;
GList *node;
hash = g_hash_table_new (g_double_hash, g_double_equal);
for (node = settings.presets; node; node = node->next) {
preset *ps;
gfloat *f;
ps = (preset *) node->data;
f = g_malloc0 (sizeof (gfloat));
*f = ps->freq;
g_hash_table_insert (hash, f, NULL);
}
void printf_key (gpointer key, gpointer value, gpointer user_data)
{
printf("\t%s\n", (char *) key);
}
void printf_hash_table (GHashTable* hash_table)
{
g_hash_table_foreach (hash_table, printf_key, NULL);
}
printf_hash_table (hash);
but without success!
this print:
���B
ff�B
ff�B
���B
ff�B
f��B
f��B
���B
33�B
ff�B
�L�B
���B
�̲B
Upvotes: 0
Views: 309
Reputation:
Your code looks correct to me except for the routine that prints out key values. I think you meant this, which will output each gfloat
value as a string:
void printf_key (gpointer key, gpointer value, gpointer user_data)
{
printf("\t%f\n", *(gfloat *) key);
}
To avoid memory leaks, you should probably also be creating your hash table like this so the memory you allocate for each key is automatically released when the table is destroyed (or a duplicate key is inserted):
hash = g_hash_table_new_full (g_double_hash, g_double_equal, g_free, NULL);
Upvotes: 1