0

How do I create and access an array of GList?

I tried this:

GList* clist[5];

for(i = 0; i<5; i++)
        clist[i]=g_list_alloc();

clist[0] = g_list_append(clist[0], five);

but it doesn't work, it gives me a segfault, I'm guessing i'm not allocating memory for clist correctly.

Stewie Griffin
  • 14,889
  • 11
  • 39
  • 70
user103052
  • 51
  • 1
  • 2

1 Answers1

2

You're misunderstanding g_list_alloc. It is used to allocate a single link, not to create a list. The g_list_* functions accept NULL pointers to mean an empty list, so all you really do to "create" an empty list is set the pointer to NULL. That means you can get rid of your loop, and just do:

GList* clist[5] = { NULL, };

A more complete example:

int i, j;
/* Make clist an array of 5 empty GLists. */
GList* clist[5] = { 0, };

/* Put some dummy data in each list, just to show how to add elements.  In
   reality, if we were doing it in a loop like this we would probably use
   g_list_prepend and g_list_reverse when we're done—see the g_list_append
   documentation for an explanation. */
for(i = 0; i<5; i++) {
  for(j = 0; j<5; j++) {
    clist[i] = g_list_append (clist[i], g_strdup_printf ("%d-%d", i, j));
  }
}

/* Free each list. */
for(i = 0; i<5; i++) {
  if (clist[i] != NULL) {
    g_list_free_full (clist[i], g_free);
  }
}
nemequ
  • 16,623
  • 1
  • 43
  • 62