顺序很重要。以下代码将输出: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;
}
无符号整数是一个32位的整数,占用4个字节。内存在内存中连续分配。
Option 2:
无符号整数是一个32位的整数,占用4个字节。内存是在内存中连续分配的。
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