計算機科学のブログ

ほしい物リスト

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

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

Makefile

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

コード

main.c

#include <stdio.h>
typedef struct
{
    const char *name;
    const char *species;
    int teeth;
    int age;
} fish;

void catalog(fish f)
{
    printf("%sは%sであり、歯は%i本あります。年齢は%i才です。\n",
           f.name, f.species, f.teeth, f.age);
}
int main()
{
    fish snappy = {"スナッピー", "ピラニア", 69, 4};
    catalog(snappy);
}

入出力結果(Terminal, Zsh)

% make
cc main.c && ./a.out
スナッピーはピラニアであり、歯は69本あります。年齢は4才です。
%