C - 構造体、共用体、ビットフィールド - 独自の構造を使う - フィールド 1
Head First C ―頭とからだで覚えるCの基本、 David Griffiths(著)、 Dawn Griffiths(著)、 中田 秀基(監修)、 木下 哲也(翻訳)、 O’Reilly Media)の 5章(構造体、共用体、ビットフィールド - 独自の構造を使う)、p.228(長いエクササイズ)の解答を求めてみる。
Makefile
main: main.c
cc main.c && ./a.out
コード
main.c
#include <stdio.h>
struct exercise
{
const char *description;
float duration;
};
struct meal
{
const char *ingredients;
float weight;
};
struct preferences
{
struct meal food;
struct exercise exercise;
};
struct fish
{
const char *name;
const char *species;
int teeth;
int age;
struct preferences care;
};
void catalog(struct fish f)
{
printf("%sは%sであり、歯は%i本あります。年齢は%i才です。\n",
f.name, f.species, f.teeth, f.age);
}
void label(struct 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()
{
struct fish snappy = {"スナッピー", "ピラニア", 69, 4, {{"肉", 0.1}, {"ジャグジーでの泳ぎ", 7.5}}};
label(snappy);
}
入出力結果(Terminal, Zsh)
% make
cc main.c && ./a.out
名前:スナッピー
種類:ピラニア
69本の歯、4才
餌は0.10キロの肉を与え、ジャグジーでの泳ぎを7.50時間行わせます。
%