Memory Alignment in Structures


#include <iostream>
struct POINTER
{
    void* ptr;
};

struct A
{
    char a;
};

struct B
{
    char a;
    char b;
};

struct C
{
    char a;
    int b;
    long c;
};

struct C1
{
    char a;
    short d;
    char f;
    char e;
    int b;
    long c;
};

struct C2
{
    int a;
    char d;
    int f;
    char e;
    int b;
    long c;  ///6*4
};

struct C3
{
    char d;
    char e;
    int a;
   
    int f;
  
    int b;
    long c;  ///5*4
};


union MyUnion
{
    long c;
    int a;
    char b[12];
};
struct D
{
    long c;
    char a;
    int b;
};

struct E
{
    char a;
    long c;
    int b;
};

struct F
{
    char a;
    long c;
    char b;
};

struct G
{
    char a;
    long c;
    F b;
};

struct H
{
    char a;
    char b;
    short c;
};

struct I
{
    char a;
    char b;
    int c;
};

struct EMPTY_CLASS
{
};

struct EMPTY_CLASS_WITH_VIRTUAL
{
    virtual ~EMPTY_CLASS_WITH_VIRTUAL() {}
};

#define CALC_STRUCT_SIZE(T) \
    std::cout <<"size of type " << #T << " is " << sizeof(T) << std::endl;

int main(int argc, char** argv)
{
    CALC_STRUCT_SIZE(A);
    CALC_STRUCT_SIZE(B);
    CALC_STRUCT_SIZE(C);
    CALC_STRUCT_SIZE(C1);
    CALC_STRUCT_SIZE(C2);
    CALC_STRUCT_SIZE(C3);  //save memory than C2
    CALC_STRUCT_SIZE(MyUnion);
    CALC_STRUCT_SIZE(D);
    CALC_STRUCT_SIZE(E);
    CALC_STRUCT_SIZE(F);
    CALC_STRUCT_SIZE(G);
    CALC_STRUCT_SIZE(H);
    CALC_STRUCT_SIZE(I);

    CALC_STRUCT_SIZE(EMPTY_CLASS);
    CALC_STRUCT_SIZE(EMPTY_CLASS_WITH_VIRTUAL);

    CALC_STRUCT_SIZE(char*);
    CALC_STRUCT_SIZE(short*);
    CALC_STRUCT_SIZE(int*);
    CALC_STRUCT_SIZE(long*);
    CALC_STRUCT_SIZE(void*);
    CALC_STRUCT_SIZE(F*);
    CALC_STRUCT_SIZE(POINTER);
        return 0;
}


Note that in a 64-bit system, the size of the pointer address is long long, 8 bytes 

The number of bytes of long data needs to be paid attention to. Simply put, you can see the following table

Because I tested the above example under win64, long is 4 bytes, if it is under liunx, it is 8 bytes

reference:

C++ Byte Alignment

Guess you like

Origin blog.csdn.net/qq_31638535/article/details/128857318