#pragma pack structure alignment

1. "In-depth understanding of computer systems" P191 after-school questions:

Note: It is written in the book that long is 8 bytes, but the VS compiler of win32-64 is 4 bytes.

#pragma pack(8)
typedef struct
{
    
    
    char* a;//8 8
    short b;//2 10
    double c;//8 24
    char d;//1+3 28
    float e;//4 32
    char f;//1+3 36
    long g;//4 40
    int h;//4+4 48
}test_size_t;
#pragma pack()

2. #pragma pack(n) instruction

Specifies the number of bytes to align

#pragma pack(2)
typedef struct
{
    
    
    char* a;//8 8
    short b;//2 10
    double c;//8 18
    char d;//1+1 20
    float e;//4 24
    char f;//1+1 26
    long g;//4 30
    int h;//4 34
}test_size_t;
#pragma pack()

3. Principle: Members are arranged from small to large

#pragma pack(8)
typedef struct
{
    
    
    char d;
    char f;
    short b;
    float e;
    long g;
    int h;
    double c;
    char* a;
}test_size_t_min;
#pragma pack()

4. Use #pragma pack(1) to parse the byte data stream to a given structure, no byte offset is required for parsing;


reference:

1. Detailed usage of #pragma pack_Machine Vision 001 Blog-CSDN Blog

2. #pragma pack() Interpretation_HUSTER593's Blog-CSDN Blog

Guess you like

Origin blog.csdn.net/KPer_Yang/article/details/130025373