版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/qq_40818798/article/details/86688479
#include <stdio.h>
#define N 8 //1 2 4 8 ...
#pragma pack(N) //N字节对齐开始
struct st1
{
int a; //N=1 4; N=2 4; N=4 4; N=8 4
char b; //N=1 1; N=2 2; N=4 2; N=8 2
short c; //N=1 2; N=2 2; N=4 2; N=8 2
}s1; //N=1 7; N=2 8; N=4 8; N=8 8
struct st2
{
char a; //N=1 1; N=2 2; N=4 4; N=8 4
int b; //N=1 4; N=2 4; N=4 4; N=8 4
short c; //N=1 2; N=2 2; N=4 4; N=8 4
}s2; //N=1 7; N=2 8; N=4 12; N=8 12
struct st3
{
int a; //N=1 4; N=2 4; N=4 4; N=8 4
struct st1 s; //N=1 7; N=2 8; N=4 8; N=8 12
double b; //N=1 8; N=2 8; N=4 8; N=8 8
int c; //N=1 4; N=2 4; N=4 4; N=8 8
}s3; //N=1 23; N=2 24; N=4 24; N=8 32
struct st4
{
char sex; //N=1 1; N=2 2; N=4 4; N=8 4
int length; //N=1 4; N=2 4; N=4 4; N=8 4
char name[10]; //N=1 10; N=2 10; N=4 12; N=8 12
}s4; //N=1 15; N=2 16; N=4 20; N=8 20
#pragma pack() //N字节对齐结束
int main()
{
printf("%d字节对齐\n", N);
printf("sizeof(st1):%d\n", sizeof(struct st1));
printf("&a:%p &b:%p &c:%p\n", &s1.a, &s1.b, &s1.c);
printf("sizeof(st2):%d\n", sizeof(struct st2));
printf("&a:%p &b:%p &c:%p\n", &s2.a, &s2.b, &s2.c);
printf("sizeof(st3):%d\n", sizeof(struct st3));
printf("&a:%p &s:%p &b:%p &c:%p\n", &s3.a, &s3.s, &s3.b, &s3.c);
printf("sizeof(st4):%d\n", sizeof(struct st4));
printf("&sex:%p &length:%p &name:%p\n", &s4.sex, &s4.length, &s4.name);
return 0;
}