2013-11-04 89 views
0

如何創建和訪問GList數組?你如何創建一個GList數組?

我嘗試這樣做:

GList* clist[5]; 

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

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

,但它不能正常工作,它給了我一個段錯誤,我猜我不是針對CLIST正確地分配內存。

回答

2

你誤解了g_list_alloc。它用於分配單個鏈接,而不是創建列表。 g_list_ *函數接受空指針來表示一個空列表,所以你真正要做的「創建」一個空列表的時候將指針設置爲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); 
    } 
}