《结构体内存对齐与位段》
如果对结构体内存对齐还不是很理解的话,做题之前可以看一看喔,看完轻轻松松就可以做出了啦。如果懂的话,请做题吧!
第一题:
在32位系统环境,编译选项为4字节对齐,那么sizeof(A)和sizeof(B)是( ?)
struct A
{
int a;
short b;
int c;
char d;
};
struct B
{
int a;
short b;
char c;
int d;
};
int main()
{
printf("%d\n", sizeof(struct A));
printf("%d\n", sizeof(struct B));
return 0;
}
A.16,16
B.13,12
C.16,12
D.11,16
结果:
第二题
下面代码的结果是:( ? )
#pragma pack(4)/*编译选项,表示4字节对齐 平台:VS2013。语言:C语言*/
int main(int argc, char* argv[])
{
struct tagTest1
{
short a;
char d;
long b;
long c;
};
struct tagTest2
{
long b;
short c;
char d;
long a;
};
struct tagTest3
{
short c;
long b;
char d;
long a;
};
struct tagTest1 stT1;
struct tagTest2 stT2;
struct tagTest3 stT3;
printf("%d %d %d", sizeof(stT1), sizeof(stT2), sizeof(stT3));
return 0;
}
#pragma pack()
A.12 12 16
B.11 11 11
C.12 11 16
D.11 11 16
结果:
解析:
第三题:
在VS2013下,默认对齐数为8字节,这个结构体所占的空间大小是( ? )字节
typedef struct{
int a;
char b;
short c;
short d;
}AA_t;
A.16
B.9
C.12
D.8
结果:
解析: