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.

Nathan Pakovskie is an esteemed senior developer and educator in the tech community, best known for his contributions to Geekpedia.com. With a passion for coding and a knack for simplifying complex tech concepts, Nathan has authored several popular tutorials on C# programming, ranging from basic operations to advanced coding techniques. His articles, often characterized by clarity and precision, serve as invaluable resources for both novice and experienced programmers. Beyond his technical expertise, Nathan is an advocate for continuous learning and enjoys exploring emerging technologies in AI and software development. When he’s not coding or writing, Nathan engages in mentoring upcoming developers, emphasizing the importance of both technical skills and creative problem-solving in the ever-evolving world of technology. Specialties: C# Programming, Technical Writing, Software Development, AI Technologies, Educational Outreach

Leave a Reply

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

Back To Top