重要なのは順序です。次のコードは出力を提供します: 8
#include<stdio.h>
typedef struct size
{
unsigned int b:32;
unsigned int a:1;
unsigned int c:1;
}mystruct;
int main(int argc, char const *argv[])
{
mystruct a;
printf("\n %lu \n",sizeof(a));
return 0;
}
unsigned int は 32 ビット整数で、4 バイトを占有します。メモリはメモリ内で連続して割り当てられます。
オプション1:
unsigned int a:1; // First 4 bytes are allocated
unsigned int b:31; // Will get accomodated in the First 4 bytes
unsigned int c:1; // Second 4 bytes are allocated
出力: 8
オプション 2:
unsigned int a:1; // First 4 bytes are allocated
unsigned int b:32; // Will NOT get accomodated in the First 4 bytes, Second 4 bytes are allocated
unsigned int c:1; // Will NOT get accomodated in the Second 4 bytes, Third 4 bytes are allocated
出力: 12
オプション 3:
unsigned int a:1; // First 4 bytes are allocated
unsigned int b:1; // Will get accomodated in the First 4 bytes
unsigned int c:1; // Will get accomodated in the First 4 bytes
出力: 4
オプション 4:
unsigned int b:32; // First 4 bytes are allocated
unsigned int a:1; // Second 4 bytes are allocated
unsigned int c:1; // Will get accomodated in the Second 4 bytes
出力: 8