C/C+语言struct深层探索(二)

2. struct的成员对齐

  Intel、微软等公司曾经出过一道类似的面试题:

1. #include <iostream.h>

2. #pragma pack(8)
3. struct example1
4. {
5. short a;
6. long b;
7. };

8. struct example2
9. {
10. char c;
11. example1 struct1;
12. short e;
13. };
14. #pragma pack()

15. int main(int argc, char* argv[])
16. {
17. example2 struct2;

18. cout << sizeof(example1) << endl;
19. cout << sizeof(example2) << endl;
20. cout << (unsigned int)(&struct2.struct1) - (unsigned int)(&struct2)
<< endl;

21. return 0;
22. }

  问程序的输入结果是什么?

  答案是:

8
16
4

你可能感兴趣的:(struct)