内存对齐规则
- #include "stdafx.h"
- //#pragma pack(8) 和环境有关 window系统默认为8 linux为4
- #if 0
- 内存对齐本质是 牺牲空间来换取时间
- ----内存对齐规则:
- (1):取pack(n),取结构体中最大变量类型的大小m(char short int)
- n=8 m=4; 取俩数的小值 Y=4 外对齐(Y为外对齐)
- (2):1(char) 2(short) 4(int)(实际类型大小) 比出一系列内对齐规则 X 1 2 4
- (将实际类型大小和Y值进行比较,取其中的小者得到x)
- (3):所谓的内对齐(起始地址为0),就是地址值能被x整除的地方开始存放数据
- (地址的值/X 如果能整除则从此处存放)
- (4):所谓的外对齐,就是结束地址,是外对齐的最小整数倍
- (结尾可根据实际情况而定)
- -------------------------------------------------------------
- //结构体内为 char double float short
- n 8 m 8 Y 8
- 1 8 4 2 X 1 8 4 2
- 如果#pragma pack(1)取1了
- n 1 m 8 Y 1
-
- 1 8 4 2 X 1 1 1 1 实际大小除以X都能除尽
- 则按照规则就是依次存放
- 所以大小为 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;
- }
原博客地址:https://blog.csdn.net/swordarcher/article/details/78546429