計算機科学のブログ

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

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

Makefile

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

コード

main.c

#include <stdio.h>
typedef struct
{
    const char *description;
    float value;
} swag;
typedef struct
{
    swag *swag;
    const char *sequence;
} combination;
typedef struct
{
    combination numbers;
    const char *make;
} safe;
int main()
{
    swag gold = {"GOLD!", 1000000.0};
    combination numbers = {&gold, "6520"};
    safe s = {numbers, "RAMACON250"};
    puts(s.numbers.swag->description);
}

入出力結果(Terminal, Zsh)

% make
cc main.c && ./a.out
GOLD!
%