用户空间不用自己编写数据结构,使用GLIB的工具是一个非常好的方式,下面的代码展示GLIB的链表的编程示例
#include <stdlib.h>
#include <stdio.h>
#include <glib.h>
/*
* 需要安装
* yum install glib2-devel.x86_64
*
* 编译方法
* gcc glist_eg.c -g -O0 -lglib-2.0 -I /usr/include/glib-2.0/ `pkg-config --cflags glib-2.0` -o glist_eg
*/
void test1(void){
printf("\n--------------run %s ----------------\n", __FUNCTION__);
GSList* list = NULL;
list = g_slist_append(list, "second");
list = g_slist_prepend(list, "first");
g_printf("The list is now %d items long\n", g_slist_length(list));
list = g_slist_remove(list, "first");
g_printf("The list is now %d items long\n", g_slist_length(list));
g_slist_free(list);
printf("\n------------------------------------\n");
return ;
}
void test2(void){
GSList* list = NULL;
printf("\n--------------run %s ----------------\n", __FUNCTION__);
list = g_slist_append(list, "first");
list = g_slist_append(list, "second");
list = g_slist_append(list, "second");
list = g_slist_append(list, "third");
list = g_slist_append(list, "third");
g_printf("The list is now %d items long\n", g_slist_length(list));
list = g_slist_remove(list, "second");
list = g_slist_remove_all(list, "third");
g_printf("The list is now %d items long\n", g_slist_length(list));
g_slist_free(list);
printf("\n------------------------------------\n");
return;
}
void test3(void){
GSList* list = NULL;
printf("\n--------------run %s ----------------\n", __FUNCTION__);
list = g_slist_append(list, "first");
list = g_slist_append(list, "second");
list = g_slist_append(list, "third");
g_printf("The last item is '%s'\n", g_slist_last(list)->data);
g_printf("The item at index '1' is '%s'\n", g_slist_nth(list, 1)->data);
g_printf("Now the item at index '1' the easy way: '%s'\n", g_slist_nth_data(list, 1));
g_printf("And the 'next' item after first item is '%s'\n", g_slist_next(list)->data);
g_slist_free(list);
printf("\n------------------------------------\n");
return;
}
typedef struct st_person{
char name[10];
int shoe_size;
} Person;
void test4(void){
GSList* slist = NULL;
printf("\n--------------run %s ----------------\n", __FUNCTION__);
Person* tom = (Person*)malloc(sizeof(Person));
memset(tom, 0x0, sizeof(tom));
strcpy(tom->name, "Tom");
tom->shoe_size = 12;
slist = g_slist_append(slist, tom);
Person* fred = g_new0(Person, 1);
strcpy(fred->name, "Fred");
fred->shoe_size = 11;
slist = g_slist_append(slist, fred);
g_printf("Tom's shoe size is '%d'\n", ((Person*)slist->data)->shoe_size);
g_printf("Tom's shoe name is '%s'\n", ((Person*)(g_slist_nth(slist, 0)->data))->name);
g_printf("fred shoe size is '%d' \n", ((Person*)(g_slist_nth_data(slist,1)))->shoe_size);
g_printf("The last Person's name is '%s'\n", ((Person*)g_slist_last(slist)->data)->name);
/*注意释放链表并不会释放数据,需要手工进行*/
g_slist_free(slist);
free(tom);
g_free(fred);
printf("\n-----------------------


1442

被折叠的 条评论
为什么被折叠?



