Click here to Skip to main content
15,910,787 members
Please Sign up or sign in to vote.
5.00/5 (1 vote)
See more:
Hello Guys,

I am not clear with size of class on altering order of variables.

See below class: It gives me size as 20 bytes

C#
class A
{
public:
        int int1;
        int int2;
        int i;
        long l;
        short s;
        char c;



};


whereas, if I change size of order of char c ( put at the start of class)

C#
class A
{
public:
        char c;
        int int1;
        int int2;
        int i;
        long l;
        short s;
};


Now, I see size of class becomes as 24 bytes.
can you please explain this?


Regards,
Joy
Posted
Comments
Sergey Alexandrovich Kryukov 11-Apr-14 2:29am    
It depends on implementation and alignment in structures. Could you tell use the size of each of these integer types?
—SA

1 solution

The size of a structure is depending on the alignment of the members, this can be influenced by the compiler default settings, or by explicit setting alignment (e.g. #pragma pack() for VisualC++ http://msdn.microsoft.com/en-us/library/2e70t5y1.aspx[^]). To ensure this alignment padding is added (which are unused bytes that take up space and increase the size required to store the structure.
The padding is used to avoid inefficient access to data structures that are larger than a single byte.

Here an example of significant difference in size due to suboptimal ordering of members:

(char is 1 byte, long is 4 bytes and the alignment is optimized for 4 byte single access)
C++
1 byte    char1
3 byte    <padding>
4 byte    long1
1 byte    char2
3 byte    <padding>
4 byte    long2
1 byte    char3
3 byte    <padding>
4 byte    long3
1 byte    char4
3 byte    <padding>
4 byte    long4


The whole structure was 32 bytes due to the necessary padding to align the longs to the next 4 byte boundary.

Reordering the members cut this down to 20 bytes:
C++
4 byte    long1
4 byte    long2
4 byte    long3
4 byte    long4
1 byte    char1
1 byte    char2
1 byte    char3
1 byte    char4
 
Share this answer
 
v3
Comments
Legor 11-Apr-14 6:31am    
Good explanation, should be accepted.
Steve44 11-Apr-14 10:49am    
Thanks Legor.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900