Why does the sizeof operator return a size larger for a structure than the total sizes of the structure’s members?
Why does the sizeof operator return a size larger for a structure than the
Share
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
This is because of padding added to satisfy alignment constraints. Data structure alignment impacts both performance and correctness of programs:
SIGBUS).Here’s an example using typical settings for an x86 processor (all used 32 and 64 bit modes):
One can minimize the size of structures by sorting members by alignment (sorting by size suffices for that in basic types) (like structure
Zin the example above).IMPORTANT NOTE: Both the C and C++ standards state that structure alignment is implementation-defined. Therefore each compiler may choose to align data differently, resulting in different and incompatible data layouts. For this reason, when dealing with libraries that will be used by different compilers, it is important to understand how the compilers align data. Some compilers have command-line settings and/or special
#pragmastatements to change the structure alignment settings.