关于C的struct结构的几个常见疑问。
Code:
#include<stdio.h>
struct bit{
unsigned int a0:8;
unsigned int a1:16;
unsigned int a2:8;
unsigned int b;
};
struct bit2
{
unsigned char a0;
unsigned short a1;
unsigned char a2;
unsigned int b;
};
struct nobit
{
unsigned int a;
unsigned int b;
};
int main()
{
struct bit t1;
struct bit2 t3;
struct nobit t2;
unsigned char data[8]={0xA5, 0xCE, 0x12, 0xA5, 0xB0, 0xB1, 0xB2,0xB3};
memcpy( &t1, data, 8);
memcpy( &t2, data, 8);
memcpy( &t3, data, 8);
printf("++ sizeof(t1)=%d, sizeof(t3)=%d, sizeof(t2)=%d \n",
sizeof(t1), sizeof(t3), sizeof(t2) );
printf("++ t1.a0=%2x t1.a1=%4x t2.a2=%2x t1.b=%8x \n", t1.a0, t1.a1, t1
.a2, t1.b);
printf("++ t3.a0=%2x t3.a1=%4x t3.a2=%2x t3.b=%8x \n", t3.a0, t3.a1, t3
.a2, t3.b);
printf("++ t2.a=0x%8x t2.b=%8x \n", t2.a, t2.b);
return 0;
}
//运行结果:<Linux 2.6.18 X86>
++ sizeof(t1)=8, sizeof(t3)=12, sizeof(t2)=8
++ t1.a0=a5 t1.a1=12ce t2.a2=a5 t1.b=b3b2b1b0
++ t3.a0=a5 t3.a1=a512 t3.a2=b0 t3.b=bfb59d7c
++ t2.a=0xa512cea5 t2.b=b3b2b1b0
//结果说明:
1. struct对齐。
2. little_endian.
3.__LITTLE_ENDIAN_BITFIELD (这个测试还看不出来。)
0xA5, 0xCE, 0x12, 0xA5, 0xB0, 0xB1, 0xB2,0xB3
bit: | a0 | a1 | a2 | b |
bit2 | a0 | | a1 | a2 | | b |
nobit| a | b |
end.