Mae向きなブログ

Mae向きな情報発信を続けていきたいと思います。

構造体について

現在,『Write Great Code〈Vol.1〉ハードウェアを知り、ソフトウェアを書く』に引き続き,『Write Great Code〈Vol.2〉低いレベルで考え高いレベルで書く』を読んでいます。
全部で16章構成ですが,第9章の「配列データ型」まで読み進めてきました。

読み進めていくと,自分でも知らないことがたくさんあって勉強になります。
今までアセンブラレベルで考えたことはなく,プログラムを書くときは,良いデータ構造とアルゴリズムさえ,しっかりと押さえておけば良いと思っていました。それが,本書を読み進めるうちに,それだけではなく,アセンブラレベルでどうなっているかということを意識しながら,高級言語でプログラムを組むことも大切なんだと思えるようになってきました。

恥ずかしながら,構造体がメモリ上でどのように確保されるのかということを今,知りました。
以下では,5, 9, 13, 32, 33バイトの大きさの構造体で試しています。

struct_size_test.c

#include <stdio.h>

/* 5バイト */
typedef struct {
  char one_byte;
  int four_byte;
} Five_bytes;

/* 9バイト */
typedef struct {
  int four_bytes;
  int four_more_bytes;
  char one_byte;
} Nine_bytes;

/* 13バイト */
typedef struct {
  int four_bytes;
  double eight_more_bytes;
  char one_byte;
} Thirteen_bytes;

/* 32バイト */
typedef struct {
  double eight_bytes;
  double eight_more_bytes;
  float sixteen_bytes[4];
} Thirty_two_bytes;

/* 33バイト */
typedef struct {
  char one_byte;
  double eight_bytes;
  double eight_more_bytes;
  float sixteen_bytes[4];
} Thirty_three_bytes;

int main(void)
{
  printf("Five_bytes's size = %d\n", sizeof(Five_bytes));
  printf("Nine_bytes's size = %d\n", sizeof(Nine_bytes));
  printf("Thirteen_bytes's size = %d\n", sizeof(Thirteen_bytes));
  printf("Thirty_tow_bytes's size = %d\n", sizeof(Thirty_two_bytes));
  printf("Thirty_three_bytes's size = %d\n", sizeof(Thirty_three_bytes));

  return 0;
}

実行結果

環境は,

です。

$ gcc -version
i686-apple-darwin9-gcc-4.0.1: no input files
$ gcc struct_size_test.c -o struct_size_test
$ ./struct_size_test
Five_bytes's size = 8
Nine_bytes's size = 12
Thirteen_bytes's size = 16
Thirty_tow_bytes's size = 32
Thirty_three_bytes's size = 36

結果を見てみると,4の倍数の大きさのメモリが使用されていることが分かります。