gpt4 book ai didi

c - 将 float 存储为 GashTable 中的键

转载 作者:行者123 更新时间:2023-11-30 15:30:37 25 4
gpt4 key购买 nike

您好,我想知道考虑到没有 GFLOAT_TO_POINTER 宏方法,是否可以将 float 作为键存储到 GhashTable 中。

我正在遵循 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

最佳答案

除了打印出键值的例程之外,您的代码对我来说看起来是正确的。我想你的意思是这个,它将输出每个 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);

关于c - 将 float 存储为 GashTable 中的键,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25526740/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com