2

I want to achieve having a linked list in which every link stores 2 integer values. I wanted to achieve this by putting a nested struct inside the glist link. But I get an error which states that my struct is an incompatible data type. What should I do now? I wrote the following Program:

       #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);
}

I would appreciate any help with this. I would think there could be a possibility to add 2 integers into the glist link directly but I don't know how I should do that.

3
  • Err..., IMHO the correct idiom is client_datalist=g_list_append (client_datalist, tempstruct);. If you do not keep the return value of the initial call on g_list_append, you will just leak the memory used by the newly created list element. Additionally a GList is not a C++ container: it only stores pointers to objects and the caller is responsable for allocating and freeing the objects. Commented Sep 22, 2024 at 16:27
  • Creating a type-alias is like typedef actual_type alias_name;. You have forgotten the alias_name part, and only defined the structure tag and type. The struct client_data { ... } is the actual_type part in your code. That should give build errors. Commented Sep 22, 2024 at 16:27
  • Also, once you have defined a type-alias, it works like any other type (like for example int). You could do e.g. typedef struct foo { /* some members... */ } bar; and use bar as the type: bar my_foo_structure; Commented Sep 22, 2024 at 16:30

1 Answer 1

2

What you can try to pass a pointer to the data to be stored in the list

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);
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.