C/Question on size of structure and #pragma directive
Expert: Narendra - 8/16/2007
QuestionDear Narendra,
I have one question on size of structures
My question: I tried to get size of structure using sizeof operator.But i found that it is giving different answer rather than i expected(sum of sizeof all variables in structure). That answer is also changing if we change the order of variables in the structure.
After i used preprocessor directive #pragma pack(1)before structure declaration. Then it's giving expected answers.
I would like to get clarity on the following...
1>> Why the size of the structure varying by changing variable order in the structure.
2>> What is the exact procedure for structure storage
3>> Structure padding details and #pragma pack affect on this padding.
I am very much thankful if you send very clear picture on this.
Thanks in advance
--Naren
AnswerHi,
Refer the following two pages to get it clarified:
1.
http://tucupi.cptec.inpe.br/sx4/sx4man2/g1af02e/chap3.html#3.8.1
2.
http://www.codeguru.com/forum/showthread.php?t=276622
In short, the simple answer is "alignment". It tries to align each member to a 4-byte word boundary and as the order changes, this also changes. And that's the reason you are seeing different values.
If you use the 'pack' directive, then it will not try to align to word boundary and uses as less space as possible. You can even specify the number of bits to use. For example, a character uses 8 bits. And you know that, the character member of your structure uses only 4 bits, then you can use the ':' operator inside structure to specify it ti pack the char variable within 4 bits.
Regards,
Narendra