計算機科学のブログ

C - データ構造と動的メモリ - 架け橋を築く - 空間の開放, free関数

Head First C ―頭とからだで覚えるCの基本David Griffiths(著)、 Dawn Griffiths(著)、 中田 秀基(監修)、 木下 哲也(翻訳)、 O’Reilly Media)の 6章(データ構造と動的メモリ - 架け橋を築く)、p.289(自分で考えてみよう)の解答を求めてみる。

Makefile

main: main.c
	cc main.c && ./a.out

コード

main.c

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

typedef struct island
{
    char *name;
    char *opens;
    char *closes;
    struct island *next;
} island;
island *create(char *name)
{
    island *i = malloc(sizeof(island));
    i->name = strdup(name);
    i->opens = "09:00";
    i->closes = "17:00";
    i->next = NULL;
    return i;
}
void release(island *start)
{
    island *next = NULL;
    for (island *i = start; i != NULL; i = next)
    {
        next = i->next;
        free(i->name);
        free(i);
    }
}
void display(island *start)
{
    for (island *i = start; i != NULL; i = i->next)
    {
        printf("名前:%s 営業時間:%s-%s\n",
               i->name, i->opens, i->closes);
    }
}
int main()
{
    island *start = NULL;
    island *i = NULL;
    island *next = NULL;
    char name[80];
    for (; fgets(name, 80, stdin) != NULL; i = next)
    {
        next = create(name);
        if (start == NULL)
        {
            start = next;
        }
        if (i != NULL)
        {
            i->next = next;
        }
    }
    display(start);
    release(start);
}

入出力結果(Terminal, Zsh)

% make
cc main.c && ./a.out
a
b
c
d
e
名前:a
 営業時間:09:00-17:00
名前:b
 営業時間:09:00-17:00
名前:c
 営業時間:09:00-17:00
名前:d
 営業時間:09:00-17:00
名前:e
 営業時間:09:00-17:00
%