Reputation: 51
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.
Upvotes: 0
Views: 552
Reputation: 17492
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);
}
}
Upvotes: 2