#include <stdio.h> #include <stdlib.h> #include <unistd.h> struct _address { int age; char *name; struct _address *next; }; int main(void) { struct _address *users; struct _address **pt; /* 3件をプリセット */ pt = &users; *pt = (struct _address*)malloc(sizeof(struct _address)); (*pt)->name = "hogeo1"; (*pt)->age = 21; pt = &(*pt)->next; *pt = (struct _address*)malloc(sizeof(struct _address)); (*pt)->name = "hogeo2"; (*pt)->age = 22; pt = &(*pt)->next; *pt = (struct _address*)malloc(sizeof(struct _address)); (*pt)->name = "hogeo3"; (*pt)->age = 23; (*pt)->next = NULL; /* 末尾をサーチ */ for (pt = &users; *pt != NULL; pt = &(*pt)->next); /* 現在 pt はチェインテーブルの最終メンバーを指す next ポインタを指している。 * * users * | * | +======+ +======+ +======+ * +->| name | +->| name | +->| name | * +------+ | +------+ | +======+ * | age | | | age | | | age | * +------+ | +------+ | +------+ * | next |--+ | next |--+ | next | <- NULL * +======+ +->+======+ +======+ * | * pt */ /* 1件追加 */ *pt = (struct _address*)malloc(sizeof(struct _address)); (*pt)->name = "geko"; (*pt)->age = 24; (*pt)->next = NULL; /* 全件表示 */ for (pt = &users; *pt != NULL; pt = &(*pt)->next) { printf("name = %s, age = %d\n", (*pt)->name, (*pt)->age); } /* "hogeo2"、2件目を削除 */ for (pt = &users; *pt != NULL; pt = &(*pt)->next) { if (!strcmp((*pt)->name, "hogeo2")) { /* あとでfreeを呼ぶ必要があるため、削除されるポインタを待避 */ struct _address *bk = *pt; /* チェインテーブルを切りつめる */ *pt = (*pt)->next; /* テーブルから切り離された領域を開放 */ free(bk); break; } } /* 全件表示 */ for (pt = &users; *pt != NULL; pt = &(*pt)->next) { printf("name = %s, age = %d\n", (*pt)->name, (*pt)->age); } return 0; } |