1.什么是字节对齐
- 一个变量占用n个字节,则该变量的起始地址必须是n的整数倍。即(存放起始地址%n=0)
- 如果是结构体,那么结构体的起始地址是结构体中最宽的那个成员的整数倍
- 是一种牺牲空间换取时间的策略
2.不按照字节对齐
当对空间要求较高的时候,可以通过#pragma pack(n)来改变结构体成员的对齐方式:
#include<stdio.h> void main() { #pragma pack(1) // 开始标志 这行代码表示这行下面的成员字节对齐方式不按照默认的来了 struct Test { char a; int b; }; #pragma pack() // 结束标志 return; }
- #pragma pack(n)中n用来设置变量以n字节对齐方式(取值有:1,2,4,8)
- #pragma pack()用来取消强制对齐方式
- 最终的结构体的宽度是N(最宽的成员与n对比比较小的的那个)的整数倍