C/C+语言struct深层探索

出处:PConline 2005年08月11日 作者:宋宝华 责任编辑:xietaoming

文章导读:面对一个人的大型C/C++程序时,只看其对struct的使用情况我们就可以对其编写者的编程经验进行评估。从某种程度上来说,会不会用struct,怎样用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

  不明白?还是不明白?下面一一道来:

相关快问问题
频道精选

爱很简单!教您DIY制造浪漫

爱很简单!教您DIY制造浪漫

不花钱又能表达芳心,为对方设计情人节贺卡或者壁纸之类的,相信你的花心思制作的作品也能感动对方。...[详细]

本周十大热评文章
本周十大人气文章
壁纸图赏