gpt4 book ai didi

c - 使用 Glib 向 GSList 添加自定义结构

转载 作者:太空宇宙 更新时间:2023-11-04 01:35:50 24 4
gpt4 key购买 nike

我正在尝试使用函数 g_slist_append(list, &structure) 将结构添加到单向链表。这似乎可行(它正在添加指针),但是我似乎无法在读取链表时找到查看结构中元素的方法。

我的结构是这样的:

 struct customstruct
{
int var1;
int var2;
char *string_1;
}

然后,我创建一个列表:GSList *list = NULL;

然后,我附加一个这样的结构实例:

 struct customstruct list_entry;
list_entry.var1 = 1;
list_entry.var2 = 2;
list_entry.string_1 = "String";

list = g_slist_append(list, &entry);

printf("Entry var1 = %d\n", list->data->var1);

最后一行失败,因为找不到 var1(请求不是结构或 union 的成员)。

我认为我需要将其转换为正确的类型,但我不知道如何操作。有人吗?

最佳答案

我猜 GSList 结构的 data 成员是一个 void 指针,即一个可以指向任何东西但不指向任何东西的指针'有任何其他类型的信息。

这意味着你必须使用类型转换:

((struct customstruct *) list->data)->var1

关于c - 使用 Glib 向 GSList 添加自定义结构,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14561108/

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