结构体 字节对齐的练习

  1. 分析结构体大小
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
    
        struct S1
        {
              char c1;
              double d;
              char c2;
              char c3;
        };
        struct S2
        {
              char c1;
              char c2;
              char c3;
              double d;
        };
        struct S3
        {
              char c1;
              S1 s;
              char c2;
              char c3;
        };        

  1. 分析结构体大小
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
        #pragma pack(1)
        struct S1
        {
              char c1;
              double d;
              char c2;
              char c3;
        };
        #pragma pack()
        struct S3
        {
              char c1;
              S1 s;
              char c2;
              char c3;
        };

  1. 分析结构体大小
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
    
        #pragma pack(4)
        struct S1
        {
              char c1;
              double d;
              char c2;
              char c3;
        };
        #pragma pack()
        struct S3
        {
              char c1;
              S1 s;
              char c2;
              char c3;
        };

  1. 分析结构体大小
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
        struct S1
        {
              char c1;
              double d;
              char c2;
              char c3;
        };
        #pragma pack(1)
        struct S3
        {
              char c1;
              S1 s;
              char c2;
              char c3;
        };
        #pragma pack()

updatedupdated2024-12-092024-12-09