memory alignment rules
- #include "stdafx.h"
- //#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.
- #if 0
- The essence of memory alignment is to sacrifice space for time
- ---- Memory alignment rules:
- (1): Take pack(n), take the size m of the largest variable type in the structure ( char short int )
- n=8 m=4; take the smaller value of the two numbers Y=4 outer alignment (Y is outer alignment)
- (2): 1( char ) 2( short ) 4( int ) (actual type size) Compare a series of internal alignment rules X 1 2 4
- (Compare the actual type size with the Y value, and take the smaller one to get x)
- (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
- (The value of the address /X is stored from here if it is divisible)
- (4): The so-called outer alignment is the end address, which is the smallest integer multiple of the outer alignment
- (The end can be determined according to the actual situation)
- -------------------------------------------------------------
- //The body of the structure is char double float short
- n 8 m 8 Y 8
- 1 8 4 2 X 1 8 4 2
- If #pragma pack(1) takes 1
- n 1 m 8 Y 1
-
- 1 8 4 2 X 1 1 1 1 The actual size can be divided by X
- Then according to the rules, it is stored in order
- So the size is 1+8+4+2=15
- #endif
- struct type
- {
- char a; //1
- double b; //8
- float c; //4
- short d; //2
- };
- int _tmain(int argc, _TCHAR* argv[])
- {
- printf("size=%d\n", sizeof(struct type));
- return 0;
- }
结构体的大小
- #include "stdafx.h"
- struct type
- {
- char a; //1 //空了3个字节 内存对齐的需要
- //short c; short在这个位置type大小为8
- int b; //4
- //short c; short在这个位置type大小为12
- }/*var*/; //结构体的类型 type不占空间 但var占空间
- int _tmain(int argc, _TCHAR* argv[])
- {
- struct type var;
- printf("sizeof(struct type)=%d sizeof(var)=%d\n",
- sizeof(struct type), sizeof(var));
- printf("&var.a=%p &var.b=%p\n", &var.a, &var.b);
- return 0;
- }
Original blog address: https://blog.csdn.net/swordarcher/article/details/78546429