GSList
时间: 2023-08-16 08:10:09 浏览: 53
`GSList` 是 GLib 库中的一个单向链表结构体,用于存储一系列指针。它的定义如下:
```c
typedef struct _GSList GSList;
struct _GSList
{
gpointer data;
GSList *next;
};
```
其中 `data` 指向链表中的数据,`next` 指向下一个节点。
`GSList` 提供了一系列操作链表的函数,例如 `g_slist_append()` 用于在链表尾部添加节点,`g_slist_prepend()` 用于在链表头部添加节点,`g_slist_insert()` 用于在指定位置插入节点,`g_slist_remove()` 用于删除指定节点等等。此外,还有一些用于遍历链表的函数,例如 `g_slist_foreach()` 和 `g_slist_nth_data()`。
下面是一个示例,展示如何使用 `GSList` 存储整数并遍历链表:
```c
#include <glib.h>
int main() {
GSList *list = NULL;
list = g_slist_append(list, GINT_TO_POINTER(1));
list = g_slist_append(list, GINT_TO_POINTER(2));
list = g_slist_append(list, GINT_TO_POINTER(3));
for (GSList *node = list; node != NULL; node = node->next) {
int value = GPOINTER_TO_INT(node->data);
g_print("%d\n", value);
}
g_slist_free(list);
return 0;
}
```
注意,在使用 `GSList` 存储指针时,需要使用 `GINT_TO_POINTER()` 和 `GPOINTER_TO_INT()` 进行类型转换。同时,在使用完毕后,需要调用 `g_slist_free()` 函数释放链表占用的内存。
相关推荐
![doc](https://img-home.csdnimg.cn/images/20210720083327.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![pptx](https://img-home.csdnimg.cn/images/20210720083543.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)