3

私は次の構造を持っています。サイズは側面で計算されます。構造体のサイズは、パディング後30バイトにする必要があります。ただし、サイズは28です。構造サイズ28はどうですか?

#include <stdio.h>
struct a
{
    char t;      //1 byte+7 padding byte      Total = 8bytes
    double d;    //8 bytes                    Total = 16bytes
    short s;     //2 bytes                    Total = 18Bytes
    char arr[12];//12 bytes 8+8+4+12=32.      Total = 30Bytes
};
int main(void)
{
    printf("%d",sizeof(struct a));  // O/p = 28bytes
    return 0;
}
4

6 に答える 6

6

offsetof各構造体メンバーの後の実際のパディングを知るために使用できます。

#include <stddef.h>

printf("Padding after t: %zu\n", 
    offsetof(struct a, d) - sizeof (((struct a *) 0)->t));

printf("Padding after d: %zu\n",
    offsetof(struct a, s) - offsetof(struct a, d)
    - sizeof (((struct a *) 0)->d));

printf("Padding after s: %zu\n",
    offsetof(struct a, arr) - offsetof(struct a, s)
    - sizeof (((struct a *) 0)->s));

printf("Padding after arr: %zu\n",
      sizeof(struct a) - offsetof(struct a, arr)
      - sizeof (((struct a *) 0)->arr));

書いたようR.に、あなたはおそらくの32-bitアラインメントがdouble8バイトではなく4バイトであるシステムを使用しています。

于 2012-10-22T17:24:29.970 に答える
4

バイトパディングを誤って計算しています。これは、コンパイラのオプションやその他のものに依存します。パディングの正しい値を示すために、プラグマのpackディレクティブを調べる必要があります。例えば:

#pragma pack(show)

警告を介してバイトパディングを表示する必要があります。ニーズに合わせてコードを調整するように明示的に設定することもできます。msdnで調べてください。リンクは次のとおりです http://msdn.microsoft.com/en-us/library/2e70t5y1%28v=vs.71%29.aspx

于 2012-10-22T17:24:07.290 に答える
2

64ではなく32ビット境界で整列していると思います。これはどうですか。

struct a
{
    char t;      //1 byte+3 padding bytes     Total = 4bytes
    double d;    //8 bytes                    Total = 12bytes
    short s;     //2 bytes+2 padding bytes    Total = 16Bytes
    char arr[12];//12 bytes 4+8+4+12=28.      Total = 28Bytes
};
于 2012-10-22T17:21:11.053 に答える
2

double8バイトのアライメント要件がない32ビットアーキテクチャで構築していると思われます。この場合、アライメントは次のようになります。

struct a
{
    char t;      //1 byte+3 padding byte      Total = 4bytes
    double d;    //8 bytes                    Total = 12bytes
    short s;     //2 bytes                    Total = 14Bytes
    char arr[12];//12 bytes +2 padding bytes  Total = 28Bytes
};
于 2012-10-22T17:21:55.770 に答える
1

この場合、構造体メンバーごとに、メモリは4バイトの倍数で与えられます。

char t-4バイト、double d-8バイト、short s-4バイト、chararr[12]-12バイト。

合計4(char)+8(double)+4(short)+12(char配列)=28バイト

于 2012-10-23T14:32:47.557 に答える
0

ほとんどの場合、charの後には3バイトのパディングが続き(したがって、doubleは4バイトの境界で始まります)、shortの後にも2バイトのパディングが続きます。

しかし...メンバーのオフセットを印刷して自分の目で確かめてみませんか?

于 2012-10-22T17:20:44.673 に答える