[C言語]構造体の各メンバがメモリ上にどう配置されてるか見てみた

実験コード
#include <stdio.h>

struct DATA {
    int i1;
    int i2;
    int i3;
    char c1;
    char c2;
    char c3;
    double d1;
    double d2;
    double d3;
};

int main()
{
    struct DATA mydata;
    printf("address of i1 is %p\n", &(mydata.i1));
    printf("address of i2 is %p\n", &(mydata.i2));
    printf("address of i3 is %p\n", &(mydata.i3));
    printf("address of c1 is %p\n", &(mydata.c1));
    printf("address of c2 is %p\n", &(mydata.c2));
    printf("address of c3 is %p\n", &(mydata.c3));
    printf("address of d1 is %p\n", &(mydata.d1));
    printf("address of d2 is %p\n", &(mydata.d2));
    printf("address of d3 is %p\n", &(mydata.d3));

    printf("address of mydata is %p\n", &mydata);
}
実行結果
(Windows7 32bit, gcc)
address of i1 is 0022FEF8
address of i2 is 0022FEFC
address of i3 is 0022FF00
address of c1 is 0022FF04
address of c2 is 0022FF05
address of c3 is 0022FF06
address of d1 is 0022FF08
address of d2 is 0022FF10
address of d3 is 0022FF18
address of mydata is 0022FEF8
おお、予想通り各メンバはメモリ上に並んで配置されていますね。

注目すべきは最終行です。

構造体そのもののアドレスは、なんと構造体の最初のメンバのアドレスと同じ値になっていました。
これは、配列aのアドレスが配列の最初の要素a[0]のアドレスと同じであることと似ていますね。

メンバがメモリ上に並んで配置されていることと合わせて考えると、構造体というのはメモリ的観点から見ると配列と同じようなものであることがわかりました。

これは思わぬ収穫でした。
カテゴリ: