我喜欢用程序去理解 字节对齐 与 结构体指针强转的一些概念就不重复了。可自行百度。
#pragma pack(4)//强制指定以4字节对齐 默认按结构体中成员最大字节对齐
#include <stdio.h>
#include <stdlib.h>
typedef struct TA
{
char a;
int b;
char c;
}aa;
typedef struct TB
{
char x;
int y;
char z;
}bb;
typedef struct TC
{
char c1;
char c2;
char c3;
}cc;
int main(int argc, char const *argv[])
{
aa s1;
s1.a='a';
s1.b=4;
s1.c='c';
printf("=====结构体TA=====\n");
printf("%p\n", &s1.a);
printf("%p\n", &s1.b);
printf("%p\n", &s1.c);
printf("%c\n", s1.a);
printf("%d\n", s1.b);
printf("%c\n", s1.c);
printf("%d\n",sizeof s1);
bb *s2=(bb*)(&s1);
printf("=====结构体TB=====\n");
printf("%p\n", &(s2->x));
printf("%p\n", &(s2->y));
printf("%p\n", &(s2->z));
printf("%c\n", s2->x);
printf("%d\n", s2->y);
printf("%c\n", s2->z);
printf("%d\n",sizeof *s2);
cc *s3=(cc*)(&s1);
printf("=====结构体TC=====\n");
printf("%p\n", &(s3->c1));
printf("%p\n", &(s3->c2));
printf("%p\n", &(s3->c3));
printf("%c\n", s3->c1);
printf("%c\n", s3->c2);
printf("%c\n", s3->c3);
printf("%d\n",sizeof *s3);
return 0;
}
运行结果:
=====结构体TA=====
0x7ffc49400ca0
0x7ffc49400ca4
0x7ffc49400ca8
a
4
c
12
=====结构体TB=====
0x7ffc49400ca0
0x7ffc49400ca4
0x7ffc49400ca8
a
4
c
12
=====结构体TC=====
0x7ffc49400ca0
0x7ffc49400ca1
0x7ffc49400ca2
a
@
3