实例讲解c语言结构体大小 sizeof(struct A)

发布时间 2023-07-21 08:40:08作者: SymPny
约定为32位系统,即char 1字节、short 2字节、int 4字节

该问题总结为两条规律:
1,每个结构体成员的起始地址为该成员大小的整数倍,即int型成员的其实地址只能为0、4、8等

2,结构体的大小为其中最大成员大小的整数倍

  1. #include <stdio.h>
  2. #include <stdlib.h>
  3. #include <sys/types.h>
  4. #include <sys/stat.h>
  5. #include <fcntl.h>
  6. #include <unistd.h>
  7. #include <string.h>
  8. #include <sys/ioctl.h>
  9. struct A{
  10. char a;
  11. int b;
  12. short c;
  13. };
  14. struct B{
  15. char a;
  16. short b;
  17. int c;
  18. };
  19. int main(int argc, char *argv[])
  20. {
  21. printf("sizeof(struct A)=%d, sizeof(struct B)=%d\n", sizeof(struct A), sizeof(struct B));
  22. return 1;
  23. }


结果:

分析:

  1. struct A{
  2. char a; //1
  3. int b; //空3 + 4 = 7 (规则1)
  4. short c; //2+空2=4 (规则2)
  5. };
  6. struct B{
  7. char a; //1
  8. short b; //空1 + 2 = 3 (规则1)
  9. int c; //4
  10. };

上面是问题的简化版,其实还有另外两条规则,下面严格按照定义补充完整:

1,数据类型自身对齐

数据类型的起始地址为其大小的整数倍

2,结构体的自身对齐

结构体的自身对齐值为其中最大的成员大小

3,指定对齐

可以使用关键词#pragma pack(1) 来指定结构体的对齐值

4,有效对齐值

有效对齐值为自身对齐值与指定对齐值中较小的一个。(即指定对齐值超过自身对齐值无意义)


依然使用上面的程序验证一下规则3:

  1. #include <stdio.h>
  2. #include <stdlib.h>
  3. #include <sys/types.h>
  4. #include <sys/stat.h>
  5. #include <fcntl.h>
  6. #include <unistd.h>
  7. #include <string.h>
  8. #include <sys/ioctl.h>
  9. #pragma pack(1)
  10. struct A{
  11. char a;
  12. int b;
  13. short c;
  14. };
  15. #pragma pack(1)
  16. struct B{
  17. char a;
  18. short b;
  19. int c;
  20. };
  21. int main(int argc, char *argv[])
  22. {
  23. printf("sizeof(struct A)=%d, sizeof(struct B)=%d\n", sizeof(struct A), sizeof(struct B));
  24. return 1;
  25. }
结果:

这个结果比较容易理解,struct成为了紧密型排列,之间没有空隙了。


验证规则4:

  1. #include <stdio.h>
  2. #include <stdlib.h>
  3. #include <sys/types.h>
  4. #include <sys/stat.h>
  5. #include <fcntl.h>
  6. #include <unistd.h>
  7. #include <string.h>
  8. #include <sys/ioctl.h>
  9. #pragma pack(8)
  10. struct A{
  11. char a;
  12. int b;
  13. short c;
  14. };
  15. #pragma pack(8)
  16. struct B{
  17. char a;
  18. short b;
  19. int c;
  20. };
  21. int main(int argc, char *argv[])
  22. {
  23. printf("sizeof(struct A)=%d, sizeof(struct B)=%d\n", sizeof(struct A), sizeof(struct B));
  24. return 1;
  25. }
结果:

与第一次结果相同,说明#pragma pack(8) 没有起到任何作用。