字节对齐 、pragma 、位域长度问题整理
- 结构体变量的首地址能够被其最宽基本类型成员的大小所整除;
- 结构体每个成员相对结构体首地址的偏移量(offset)都是成员大小的整数倍,如有需要编译器会在成员之间加上填充字节;
- 结构体的总大小为结构体最宽基本类型成员大小的整数倍,如有需要编译器会在最末一个成员之后加上填充字节。
#include <stdio.h> // 按结构体最宽数据类型int对齐 // char[*]多少都是按4字节对齐 struct stChar{
char a[5]; int b; char c; }; // 按结构体最宽数据类型short对齐 struct stShort{
char a; short b; }; // 按结构体最宽数据类型long对齐 struct stLong{
char a; long b; }; // 按结构体最宽数据类型int对齐 // 变量c的偏移量 要为自己大小的倍数 #pragma pack(8) //为2时,sizeof为10.为8时sizeof为12 struct AA {
int a; char b; short c; //长度2 偏移量要提升到2的倍数6;存放位置区间[6,7] char d; }; struct AAA {
// 类型说明符 位域名: 位域长度 int a:2; //变量a,4位长度,只使用两位长度 sizeof(AAA)为4 char b:1; }; int main() {
struct stChar stChar1; struct stShort stShort1; struct stLong stLong1; struct AA stAA; struct AAA stAAA; printf("stChar = [%ld]\n", sizeof(stChar1)); printf("stShort = [%ld]\n", sizeof(stShort1)); printf("stLong = [%ld]\n", sizeof(stLong1)); printf("stAA = [%ld]\n", sizeof(stAA)); printf("stAAA = [%ld]\n", sizeof(stAAA)); return 0; }
打印结果
stChar = [16] stShort = [4] stLong = [16] stAA = [12] stAAA = [4]
发布者:全栈程序员-站长,转载请注明出处:https://javaforall.net/231070.html原文链接:https://javaforall.net
