計算機科学のブログ

C - 構造体、共用体、ビットフィールド - 独自の構造を使う - 書き換え、ポインタ

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

Makefile

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

コード

main.c

#include <stdio.h>

typedef struct
{
    const char *name;
    const char *species;
    int age;
} turtle;
void happy_birthday(turtle *t)
{
    (*t).age = (*t).age + 1;
    printf("誕生日おめでとう、%s!これで%i才ですね!\n", (*t).name, (*t).age);
}
int main()
{
    turtle myrtle = {"マートル", "オサガメ", 99};
    happy_birthday(&myrtle);
    printf("%sの年齢は%i才です。\n", myrtle.name, myrtle.age);
}

入出力結果(Terminal, Zsh)

% make
cc main.c && ./a.out
誕生日おめでとう、マートル!これで100才ですね!
マートルの年齢は100才です。
%