如何在 C 中的 Glist 对象中存储一个结构体或多个变量

问题描述 投票:0回答:1

我想实现一个链表,其中每个链接存储 2 个整数值。我想通过在 glist 链接内放置一个嵌套结构来实现此目的。但我收到一个错误,指出我的结构是不兼容的数据类型。我现在该怎么办? 我写了以下程序:

       #include <glib.h>
        
/*  this is the documentation of the glist struct:
struct GList {
  gpointer data;
  GList* next;
  GList* prev;
}
*/
        typedef struct client_data {
            int int1;
            int int2;
        };
        int main(){
    
    //initialize glist
        GList *client_datalist = NULL;
    
    //Data storage which should be temporary because I want to store the data inside the list
        struct client_data tempstruct;
            tempstruct.int1 = 1;
            tempstruct.int2 = 100;
        
            g_list_append (client_datalist, tempstruct);
}

如果有任何帮助,我将不胜感激。我认为有可能直接将 2 个整数添加到 glist 链接中,但我不知道应该怎么做。

c list glib
1个回答
0
投票

您可以尝试将指针传递给要存储在列表中的数据

GList *client_datalist = NULL;

struct client_data *tempstruct = (struct client_data *)malloc(sizeof(struct client_data));
tempstruct->int1 = 1;
tempstruct->int2 = 100;

g_list_append (client_datalist, tempstruct);
© www.soinside.com 2019 - 2024. All rights reserved.