1.结构体用指针表示
#include <stdio.h>
struct s
{
char c;
int b;
};
int main(void)
{
struct s s1;
s1.c = 't';
s1.b = 12;
printf("len = %ld\n",sizeof(struct s));
char *p1 = (char *)(&s1); //将结构体用指针的方式表示
printf("*p1 = %c\n",*p1);
printf("s1.c = %c\n",s1.c);
int *p2 = (int *)((long unsigned int)&s1+4); //强制转换为int型会出现段错误
printf("*p2 = %d\n",*p2);
printf("s1.c = %d\n",s1.b);
return 0;
}
2.通过使用
#pragma pack()
~~~~~~~~~~
#pragma pack()
来制定该范围内对齐规则;
对齐原则遵循最后一个变量类型必须是对齐字节数的整数倍;
1 #include <stdio.h>
2
3 #pragma pack(8) //和第40行共同起到8字节对齐的作用
4
5
6 //结果为1的整数倍 结果为4的整数倍 结果为8的整数倍
7
8 struct a //一字节 四字节 八字节
9 {
10 char ad; //1 4 4(1+3)
11 int dfs; //4 4 4
12 double dou; //8 8 8
13
14 };
15
16 struct b //一字节 //四字节 八字节
17
18 {
19 int d; //4 4 4
20 char name[10]; //10 10 10
21 short i; //2 2 2
22 double j; //8 8 8
23 };
24
25 struct c //一字节 //四字节 八字节
26 {
27 int wq; //4 4 8
28 struct b b1; //24 24 24
29 char oe; //1 4 8
30
31 };
32
33 struct s
34 {
35 char c;
36 int b;
37
38 };
39
40 #pragma pack()
41
42 int main(void)
43 {
44 printf("sizeof(struct a) = %ld\n",sizeof(struct a));
45 printf("sizeof(struct b) = %ld\n",sizeof(struct b));
46 printf("sizeof(struct c) = %ld\n",sizeof(struct c));
47 return 0;
48}
3.用__attribute__((packed)):对类型进行1字节对齐
用__attribute__((aligned(n))):对类型整体进行n字节对齐
#include <stdio.h>
struct a
{
int sf;
char w;
short ok;
}__attribute__((packed));
int main(void)
{
printf("sizeof(struct a) = %ld\n",sizeof(struct a));
return 0;
}
#include <stdio.h>
struct a
{
char w; //4(1+3)
int sf; //4
short ok; //8(2+6)
double wf; //8
}__attribute__((aligned(8)));
int main(void)
{
printf("sizeof(struct a) = %ld\n",sizeof(struct a));
return 0;
}