Structure size and memory alignment rules

memory alignment rules

[cpp]  view plain copy  
  1. #include "stdafx.h"  
  2.   
  3. //#pragma pack(8) is related to the environment. The default value of the window system is 8, and the default value of linux is 4.  
  4.   
  5. #if 0  
  6.   
  7. The essence of memory alignment is to sacrifice space for time  
  8.   
  9. ---- Memory alignment rules:  
  10. (1): Take pack(n), take the size m of the largest variable type in the structure ( char short int )    
  11. n=8 m=4; take the smaller value of the two numbers Y=4 outer alignment (Y is outer alignment)  
  12.   
  13.   
  14. (2): 1( char ) 2( short ) 4( int ) (actual type size) Compare a series of internal alignment rules X 1 2 4      
  15. (Compare the actual type size with the Y value, and take the smaller one to get x)  
  16.   
  17.   
  18. (3): The so-called internal alignment (starting address is 0), that is, the place where the address value is divisible by x starts to store data   
  19. (The value of the address /X is stored from here if it is divisible)  
  20.    
  21.   
  22. (4): The so-called outer alignment is the end address, which is the smallest integer multiple of the outer alignment  
  23. (The end can be determined according to the actual situation)  
  24.   
  25. -------------------------------------------------------------  
  26. //The body of the structure is char double float short  
  27. n 8      m 8      Y 8  
  28. 1 8 4 2     X 1 8 4 2  
  29.   
  30. If #pragma pack(1) takes 1  
  31.   
  32. n 1      m 8      Y 1  
    1. 1 8 4 2 X 1 1 1 1 The actual size can be divided by X   
    2. Then according to the rules, it is stored in order  
    3. So the size is 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. }  

Original blog address: https://blog.csdn.net/swordarcher/article/details/78546429


Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324811517&siteId=291194637