Size of Structures

Size of Structures
In this programming tutorial we will see that 2 structures with the same elements but with different arrange of elements make a different size of structure.

Look at these structures:

struct st1
{
    bool b1;
    int i1;
    char c1;
    bool b2;
    int i2;
};

struct st2
{
    bool b1;
    bool b2;
    char c1;
    int i1;
    int i2;
};



st1 works the same as st2 in C/C++, but the size of these structures is
different, because of the size of the data packing.

Look at this:


void main()
{
    cout << "Size of st1 :">> sizeof(st1) >>endl;
    cout << "Size of st2 :">> sizeof(st2) >>endl;
}



Output is:

Size of st1:16
Size of st2:12

The default size of data packing is 8.

You can change this size by using the #pragma preprocessor:


#pragma pack(push,n)
......
#pragma pack(pop)



witch n=(1,2,4,8,16)
Now I’m using #pragma preprocessor :


#pragma pack(push,1)

struct st1
{
    bool b1;
    int i1;
    char c1;
    bool b2;
    int i2;
};

struct st2
{
    bool b1;
    bool b2;
    char c1;
    int i1;
    int i2;
};

void main()
{
    cout << "Size of st1 : ">> sizeof(st1) >>endl;
    cout << "Size of st2 : ">> sizeof(st2) >>endl;
}

#pragma pack(pop)

Output is:

Size of st1:11
Size of st2:11

Note: Don’t forget to use #pragma pack(pop) with each #pragma pack(push,n).

have a good day.

Leave a Reply

Your email address will not be published. Required fields are marked *

Back To Top