2014-08-27 22 views
0

你好我想知道是否有可能存储一个浮点作为关键入GhashTable考虑到没有GFLOAT_TO_POINTER宏方法。在GhashTable中存储float作为键

我正在按照IBM http://www.ibm.com/developerworks/linux/tutorials/l-glib/section5.html在线找到的教程进行操作,但似乎无法找到将float用作键的方法。

任何帮助将非常感谢!

typedef struct Settings settings; 
typedef struct Preset preset; 

struct Gnomeradio_Settings 
{ 
    GList *presets; 
}; 

struct Preset 
{ 
    gchar *name; 
    gfloat freq; 
}; 

我希望把所有频率从settings.presets清单为重点的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); 

但都没有成功!

本刊:

���B 
ff�B 
ff�B 
���B 
ff�B 
f��B 
f��B 
���B 
33�B 
ff�B 
�L�B 
���B 
�̲B 
+0

看到这个[答案](http://stackoverflow.com/questions/25298327/ghashtable-that-using-uint64-t-as-键 - 和 - a-结构-AS-值/ 25298461#25298461)。 – 2014-08-27 12:14:55

+1

也请参阅此答案:http://stackoverflow.com/a/6685020/390913 – perreal 2014-08-27 12:29:11

回答

1

你的代码看起来正确的我,除了打印出键值的程序。我想你的意思是这样,这将输出的每个gfloat值的字符串:

void printf_key (gpointer key, gpointer value, gpointer user_data) 
{ 
    printf("\t%f\n", *(gfloat *) key); 
} 

为了避免内存泄漏,你应该也可以创建哈希表这样的,所以你分配了每个按键的内存会自动释放当表被破坏(或重复的键被插入):

hash = g_hash_table_new_full (g_double_hash, g_double_equal, g_free, NULL); 
相关问题