如何创建和访问GList数组?
我试过了:
GList* clist[5];
for(i = 0; i<5; i++)
clist[i]=g_list_alloc();
clist[0] = g_list_append(clist[0], five);
但它不起作用,它给了我一个段错误,我猜测我没有为clist正确分配内存。
答案 0 :(得分:2)
你误解了g_list_alloc。它用于分配单个链接,而不是用于创建列表。 g_list_ *函数接受NULL指针来表示一个空列表,所以你真正要做的是“创建”一个空列表,将指针设置为NULL。这意味着你可以摆脱你的循环,只需:
GList* clist[5] = { NULL, };
更完整的例子:
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);
}
}