如何在C中添加一个浮点数到列表?



有一个很棒的C库叫做GLib。https://docs.gtk.org/glib/index.html我使用并喜欢这个。其中有一个叫做GList的结构,它是一个动态增长的结构(就像一个向量)。使用g_list_append(GList* list, gpointer* pointer)函数,我可以添加新元素,但有一个问题。如果我想添加一个整数,我可以使用GINT_TO_POINTER宏,但没有GFLOAT_TO_POINTER(但gfloat是glib中的类型)。我不想为浮点数分配内存。我如何添加一个到列表?

#include <stdio.h>
#include "glib.h"
#include <stdbool.h>
int main() {
int num = 10;
gchar* str = g_strdup("Hello");
GList* list_name = NULL;
list_name = g_list_append(list_name, GINT_TO_POINTER (4 + num * 3));
list_name = g_list_append(list_name, "Hello");
list_name = g_list_append(list_name, str);
list_name = g_list_append(list_name, GINT_TO_POINTER(num));
list_name = g_list_append(list_name, GINT_TO_POINTER((int)true));
list_name = g_list_append(list_name, GINT_TO_POINTER((int)false));
printf("%dn", *(int*)(g_list_nth(list_name, 0)));
printf("%sn", (gchar*)g_list_nth(list_name, 1)->data);
printf("%sn", (gchar*)g_list_nth(list_name, 2)->data);
printf("%dn", *(int*)(g_list_nth(list_name, 3)));
printf("%dn", *(int*)(g_list_nth(list_name, 4)));
printf("%dn", *(int*)(g_list_nth(list_name, 5)));
g_free(str);
g_list_free(list_name);
return 0;
}
~ 

这是我如何将int, bool或string添加到列表中,但我不知道如何将float添加到列表中。

我怀疑没有GFLOAT_TO_POINTER宏的原因是因为它不能保证在GLib支持的所有平台上浮点数与指针相同或更小。(参见散列表存储双精度)

虽然,看看你的代码样本,似乎你可能更好地使用结构体,因为它看起来像你的列表是固定大小的,你期望某些类型在某些索引。像这样:

struct Name {
int number1;
const char *static_str;
char *str;
int number2;
bool b1 : 1;
bool b2 : 1;
}
// ...
int num = 10;
char *str = g_strdup("Hello");
struct Name *name = g_new0(struct Name, 1);
name->number1 = 4 + num * 3;
name->static_str = "Hello";
name->str = str;
name->number2 = num;
name->b1 = true;
name->b2 = false;
g_free(name);
g_free(str);

相关内容

最新更新