Search code examples
clinked-liststructureglibsingly-linked-list

Adding custom structure to GSList with Glib


I'm trying to add a structure to a singly linked list with the function g_slist_append(list, &structure). This seems to work (it's adding the pointer), however I can't seem to find a way to view the elements in the structure when reading the linked list.

My structure looks like this:

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

Then, I make a list: GSList *list = NULL;

Then, I append one instance of the structure like this:

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

That last line fails because var1 can't be found (request for member in something not a struct or union).

I think I need to cast it to the right type but I don't know how. Anyone?


Solution

  • I'm guessing the data member of the GSList structure is a void pointer, i.e. a pointer that can point to anything but doesn't have any other type info.

    This means you have to use type-casting:

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