结构体的大小与内存对齐规则

内存对齐规则

[cpp]  view plain  copy
  1. #include "stdafx.h"  
  2.   
  3. //#pragma  pack(8)  和环境有关 window系统默认为8 linux为4  
  4.   
  5. #if 0  
  6.   
  7. 内存对齐本质是 牺牲空间来换取时间  
  8.   
  9. ----内存对齐规则:  
  10. (1):取pack(n),取结构体中最大变量类型的大小m(char short int)  
  11. n=8  m=4; 取俩数的小值  Y=4   外对齐(Y为外对齐)  
  12.   
  13.   
  14. (2):1(char) 2(short) 4(int)(实际类型大小) 比出一系列内对齐规则 X 1 2 4      
  15. (将实际类型大小和Y值进行比较,取其中的小者得到x)  
  16.   
  17.   
  18. (3):所谓的内对齐(起始地址为0),就是地址值能被x整除的地方开始存放数据   
  19. (地址的值/X 如果能整除则从此处存放)  
  20.    
  21.   
  22. (4):所谓的外对齐,就是结束地址,是外对齐的最小整数倍  
  23. (结尾可根据实际情况而定)  
  24.   
  25. -------------------------------------------------------------  
  26. //结构体内为 char double float short  
  27. n 8      m 8      Y 8  
  28. 1 8 4 2     X 1 8 4 2  
  29.   
  30. 如果#pragma  pack(1)取1了  
  31.   
  32. n 1      m 8      Y 1  
    1. 1 8 4 2     X 1 1 1 1   实际大小除以X都能除尽   
    2. 则按照规则就是依次存放  
    3. 所以大小为 1+8+4+2=15  
    4.   
    5.   
    6. #endif  
    7.   
    8.   
    9. struct type  
    10. {  
    11.     char a;   //1  
    12.     double b; //8  
    13.     float c;  //4  
    14.     short d;  //2  
    15. };  
    16.   
    17. int _tmain(int argc, _TCHAR* argv[])  
    18. {  
    19.     printf("size=%d\n"sizeof(struct type));  
    20.     return 0;  
    21. }  

结构体的大小

[cpp]  view plain  copy
  1. #include "stdafx.h"  
  2.   
  3.   
  4. struct type  
  5. {  
  6.     char a;  //1   //空了3个字节 内存对齐的需要   
  7.     //short c;  short在这个位置type大小为8  
  8.     int b;   //4  
  9.     //short c; short在这个位置type大小为12  
  10. }/*var*/;  //结构体的类型 type不占空间 但var占空间  
  11.   
  12.   
  13. int _tmain(int argc, _TCHAR* argv[])  
  14. {  
  15.     struct type var;  
  16.   
  17.     printf("sizeof(struct type)=%d  sizeof(var)=%d\n",  
  18.         sizeof(struct type), sizeof(var));  
  19.   
  20.     printf("&var.a=%p  &var.b=%p\n", &var.a, &var.b);  
  21.   
  22.     return 0;  
  23. }  

原博客地址:https://blog.csdn.net/swordarcher/article/details/78546429


猜你喜欢

转载自blog.csdn.net/m0_37962600/article/details/80063251