struct字节对齐原则

 原则1:windows下,k字节基本类型以k字节倍数偏移量对齐,自定义结构体则以结构体中最高p字节基本类型的p字节倍数偏移量对齐,Linux下则以2或4字节对齐;

 原则2:整体对齐原则,例如数组结构体,首元素字节对齐,而次元素字节未对齐,则数组元素不是字节对齐,需对尾部基本数据以结构体中最高p字节基本类型补充对齐

 作用:1节省寄存器用于保存偏移量的数量,2合理利用空间

 测试代码:

 

 1 #include <iostream>
 2 
 3 
 4 typedef struct a
 5 {
 6     char a;
 7 }A;
 8 
 9 typedef struct b
10 {
11     char a;
12     short b;
13 }B;
14 
15 typedef struct c
16 {
17     short b;
18     char a;
19 }C;
20 
21 
22 typedef struct D
23 {
24     short b;
25     char a;
26     double c;
27     char e;
28 }D;
29 
30 
31 
32 
33 using namespace std;
34 int main()
35 {
36 
37 
38     std::cout<< sizeof(A)<<std::endl;
39     std::cout<< sizeof(B)<<std::endl;
40     std::cout<< sizeof(C)<<std::endl;
41     std::cout<< sizeof(D)<<std::endl;
42 
43     return 0;
44 }

posted @ 2018-04-18 21:15  FeckCode  阅读(2132)  评论(0编辑  收藏  举报