//-- test_GSList.c --
#include <stdio.h>
#include <stdlib.h>
#include <glib.h>
typedef struct {
char* name;
int age;
} Person;
Person* persion_new(char* name, int age) {
Person* psn = g_new(Person, 1);
psn->name = name;
psn->age = age;
return psn;
}
void print_person(Person* person) {
printf("Name: %s, Age: %d\n", person->name, person->age);
}
int main(int argc, char** argv) {
GSList* list = NULL;
list = g_slist_append(list, persion_new("First", 11));
list = g_slist_append(list, persion_new("Second", 12));
printf("First age: %d, ", ((Person*) list->data)->age);
printf("First name: %s\n\n", ((Person*) g_slist_nth_data(list, 0))->name);
g_slist_foreach(list, (GFunc) print_person, NULL);
g_slist_foreach(list, (GFunc) g_free, NULL);
g_slist_free(list);
return EXIT_SUCCESS;
}
/*
$ gcc `pkg-config --cflags --libs glib-2.0` -o test_GSList test_GSList.c
$ ./test_GSList
First age: 11, First name: First
Name: First, Age: 11
Name: Second, Age: 12
*/
2010年1月16日
GLib GSList
Singly-Linked Lists
訂閱:
張貼留言 (Atom)
沒有留言:
張貼留言