某公司笔试真题。
- C/C++ code
struct Test1{ int a; double b; short c;};struct Test2{ int a; short b; double c;};struct Test3{ short a; double b; int c;};struct Test4{ short a; int b; double c;};struct Test5{ double a; int b; short c;};struct Test6{ double a; short b; int c;};void main(){ cout<<sizeof(double)<<endl; cout<<sizeof(int)<<endl; cout<<sizeof(short)<<endl; cout<<sizeof(Test1)<<endl; cout<<sizeof(Test2)<<endl; cout<<sizeof(Test3)<<endl; cout<<sizeof(Test4)<<endl; cout<<sizeof(Test5)<<endl; cout<<sizeof(Test6)<<endl; system("pause");}
[解决办法]
sizeof(struct Test1)?
[解决办法]
因为double是8字节,Test1的元素按照8字节对齐,所以应该是24字节
Test2中a和b和在一起小与8字节,所以Test2的大小是16字节
[解决办法]
结构体中的数据按照空间最大的一个变量的大小进行字节对齐
[解决办法]
1 成员的偏移地址必为自己大小的整倍
2 结构的大小必为最大成员的整倍
struct Test1{
int a; //偏移地址: 0
double b;//偏移地址: 8
short c;//偏移地址: 16
}; //已占用18个字节, 然后结构大小对齐到8的整倍, 即24
[解决办法]
void main()
{
cout<<sizeof(double)<<endl; 这个跟结构没关系8个
cout<<sizeof(int)<<endl; 一样4
cout<<sizeof(short)<<endl; 一样2
cout<<sizeof(Test1)<<endl; 24个
cout<<sizeof(Test2)<<endl; 16个
cout<<sizeof(Test3)<<endl; 24个
cout<<sizeof(Test4)<<endl; 16个
cout<<sizeof(Test5)<<endl; 16个
cout<<sizeof(Test6)<<endl; 16个
system("pause");
}
[解决办法]
考察内存对齐,结果跟平台和对齐方式有关。
[解决办法]
[解决办法]
[解决办法]