LinuxSir.cn,穿越时空的Linuxsir!

 找回密码
 注册
搜索
热搜: shell linux mysql
查看: 659|回复: 1

struct的大小,不等于各成员的大小之和?

[复制链接]
发表于 2004-5-5 17:04:27 | 显示全部楼层 |阅读模式
书上都是说struct中的成员都是按顺序存储的,总的大小就是各个成员大小之和。
以前从来都没怀疑过这个问题。
可是我刚刚测试了一下:

  1. #include <stdio.h>

  2. struct str
  3. {
  4.         int b;
  5.         char c[10];
  6. };
  7. struct str2{int a; int b; int c[10];};

  8. int
  9. main()
  10. {
  11.         struct str aa;
  12.         printf("size of struct a : %d = %d + %d\n", sizeof(struct str), sizeof(aa.b), sizeof(aa.c));
  13.         printf("size of struct2 : %d\n", sizeof(struct str2));
  14.         return 0;
  15. }
复制代码

输出结果是:
size of struct a : 16 = 4 + 10
size of struct2 : 48
这是咋回事?
发表于 2004-5-5 17:40:40 | 显示全部楼层
编译器进行了4byte对齐优化

可以使用__attribute__((packed)) 避免优化

  1. struct str
  2. {
  3.     int b;
  4.     char c[10];
  5. }__attribute__((packed));
复制代码
您需要登录后才可以回帖 登录 | 注册

本版积分规则

快速回复 返回顶部 返回列表