Chinaunix首页 | 论坛 | 博客
  • 博客访问: 424298
  • 博文数量: 126
  • 博客积分: 35
  • 博客等级: 民兵
  • 技术积分: 1262
  • 用 户 组: 普通用户
  • 注册时间: 2010-03-19 16:39
文章分类

全部博文(126)

文章存档

2017年(2)

2016年(20)

2015年(64)

2014年(24)

2013年(16)

我的朋友

分类: C/C++

2014-03-31 18:27:06

测试程序:
  1. #include <iostream>
  2. using namespace std;

  3. struct B
  4. {
  5.     int a;
  6.     char b;
  7. };

  8. struct S1
  9. {
  10.     int a;
  11.     char b;
  12.     short c;
  13.     char d;
  14. };

  15. struct S2
  16. {
  17.     int a;
  18.     char b;
  19.     short c;
  20. };

  21. struct S3
  22. {
  23.     int a;
  24.     char b;
  25.     short c;
  26.     char d;
  27.     B e;
  28. };

  29. struct S4
  30. {
  31.     int a;
  32.     char b;
  33.     short c;
  34.     char d;
  35.     B e;
  36.     char* f;
  37. };

  38. main()
  39. {
  40.     cout<< "sizeof(B):" << sizeof(B) << endl;
  41.     cout<< "sizeof(S1):" << sizeof(S1) << endl;
  42.     cout<< "sizeof(S2):" << sizeof(S2) << endl;
  43.     cout<< "sizeof(S3):" << sizeof(S3) << endl;
  44.     cout<< "sizeof(S4):" << sizeof(S4) << endl;
  45.     cout<< "sizeof(double)"<< sizeof(double) << endl;
  46.     return 0;
  47. }

64位机输出:
  1. sizeof(B):8
  2. sizeof(S1):12
  3. sizeof(S2):8
  4. sizeof(S3):20
  5. sizeof(S4):32
  6. sizeof(double)8
32位机输出:
  1. sizeof(B):8
  2. sizeof(S1):12
  3. sizeof(S2):8
  4. sizeof(S3):20
  5. sizeof(S4):24
  6. sizeof(double)8
两个准则:
1、成员的偏移量必须是成员自身大小的整数倍;
2、结构体首地址、大小都必须是最宽基本类型成员大小的整数倍;
另外,展开后的结构体的首成员的偏移量应当是被展开结构体中最宽成员大小的整数倍。
总之,一切方便系统存取数据。

参考文章:
linux下字节对齐
如何计算结构体的大小 (文章有一处错误,double在linux下应该也是8字节)
阅读(512) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~