c结构体对齐

2022/12/15

前言

c语言的字节对齐,机器的大小段模式的理解。

计算机存储的基础知识。

#include <stdio.h>
typedef struct tm{
	unsigned int a;
}TM;
typedef struct hp{
	char a;
	unsigned char b;
	TM *t;
	unsigned short c;
	unsigned long d;
}HP;

int main(int argc, char *argv[])
{
	HP hp={
		.a=0xa1,
		.b=0xb1,
		.c=0xc1c2,
		.d=0x1,
	};
	unsigned char *p=&hp;
	printf("sizeof(HP) = %lu\n",sizeof(HP) );	
	
	for (unsigned long i = 0; i < sizeof(HP); ++i) {
		printf("%02x ",p[i] );	
		if((i+1)%8==0)
			printf("\n");
	}
	unsigned int d=hp.d;
	printf("%d",d);
	
	return 0;
}
//OUT
|| sizeof(HP) = 32
|| a1 b1 00 00 00 00 00 00 
|| 00 00 00 00 00 00 00 00 
|| c2 c1 00 00 00 00 00 00 
|| 01 00 00 00 00 00 00 00 
|| 1

存储方式

	HP hp={
		.a=0xa1,
		.b=0xb1,
		.c=0xc1c2,
		.d=0xd1d2d3d4,//<-0x1
	};
//OUT
|| sizeof(HP) = 32
|| a1 b1 00 00 00 00 00 00 
|| 00 00 00 00 00 00 00 00 
|| c2 c1 00 00 00 00 00 00 
|| d4 d3 d2 d1 00 00 00 00 
|| 3520254932

字节对齐

//将 d 改为 d:1
typedef struct hp{
	char a;
	unsigned char b;
	TM *t;
	unsigned short c;
	unsigned long d:1; //<--- unsigned long d;
}HP;
//OUT
|| 1 warning generated.
|| sizeof(HP) = 24
|| a1 b1 00 00 00 00 00 00 
|| 00 00 00 00 00 00 00 00 
|| c2 c1 01 00 00 00 00 00 
|| 1

少占用了一个8字节。