c结构体对齐

前言

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

计算机存储的基础知识。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
#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;
}
1
2
3
4
5
6
7
//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

存储方式

1
2
3
4
5
6
HP hp={
.a=0xa1,
.b=0xb1,
.c=0xc1c2,
.d=0xd1d2d3d4,//<-0x1
};
1
2
3
4
5
6
7
//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

字节对齐

1
2
3
4
5
6
7
8
//将 d 改为 d:1
typedef struct hp{
char a;
unsigned char b;
TM *t;
unsigned short c;
unsigned long d:1; //<--- unsigned long d;
}HP;
1
2
3
4
5
6
7
//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字节。

0%