0

重複の可能性:
構造体パディング

プログラムは以下の通りです。

#include <iostream>

using namespace std;

struct node1 {
    int id;
    char name[4];
};

struct node2 {
    int id;
    char name[3];
};

int
main(int argc, char* argv[])
{
    cout << sizeof(struct node1) << endl;
    cout << sizeof(struct node2) << endl;
    return 0;
}

そしてコンパイラはg++ (GCC) 4.6.3です。出力は次のとおりです。

8
8

なぜそうなのか本当にわかりません。なぜsizeof(struct node2)7ではないのですか?

4

2 に答える 2

4

これは、構造が境界で整列しているためです。通常は4バイト(変更可能ですが)-つまり、構造内の各要素は少なくとも4バイトであり、要素のサイズが4バイト未満の場合は、最後にパディングが追加されます。

したがって、両方とも8バイトです。

size of int = 4
size of char = 1 
size of char array of 3 elements = 3

total size = 7, padding added (because of boundary) = +1 byte

for second structure:

sizeof int = 4
sizeof char = 1
sizeof char array of 4 elements = 4

total size = 8. no padding required. 
于 2012-10-19T19:34:07.990 に答える
1
because of Packing and byte alignment<br/>

一般的な答えは、コンパイラーは、整列の目的でメンバー間にパディングを自由に追加できるということです。または、すべてを8バイトに整列するコンパイラーがあるかもしれません。

于 2012-10-19T19:36:39.093 に答える