計算機科学のブログ

ほしい物リスト

C - 構造体、共用体、ビットフィールド - 独自の構造を使う - 入れ子

Head First C ―頭とからだで覚えるCの基本David Griffiths(著)、 Dawn Griffiths(著)、 中田 秀基(監修)、 木下 哲也(翻訳)、 O’Reilly Media)の5章(構造体、共用体、ビットフィールド - 独自の構造を使う - 分割して構築する)、p.228(長いエクササイズ)の解答を求めてみる。

Makefile

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

コード

main.c

#include <stdio.h>
typedef struct
{
    const char *description;
    float duration;
} exercise;
typedef struct
{
    const char *ingredients;
    float weight;
} meal;
typedef struct
{
    meal food;
    exercise exercise;
} preferences;
typedef struct
{
    const char *name;
    const char *species;
    int teeth;
    int age;
    preferences care;
} fish;
void label(fish a)
{
    printf("名前: %s\n種類: %s\n%i本の歯、%i才\n",
           a.name, a.species, a.teeth, a.age);
    printf("餌は%2.2fキロの%sを与え、%sを%2.2f時間行わせます。\n",
           a.care.food.weight, a.care.food.ingredients,
           a.care.exercise.description, a.care.exercise.duration);
}
int main()
{
    fish snappy = {"スナッピー", "ピラニア", 69, 4, {{"肉", 0.1}, {"ジャグジーで泳ぎ", 7.5}}};
    label(snappy);
}

入出力結果(Terminal, Zsh)

% make
cc main.c && ./a.out
名前: スナッピー
種類: ピラニア
69本の歯、4才
餌は0.10キロの肉を与え、ジャグジーで泳ぎを7.50時間行わせます。
%