sizeof structure | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 4

sizeof structure

#include <stdio.h> struct test { unsigned char first; int second; unsigned char three; struct test *fourth; }; int main() { struct test node; printf("%d\n", sizeof(node)); return 0; } In the above code the size of the structure in 64 bit processor should be 20 but why am I getting answer 24? can any one explain please.

19th Dec 2020, 3:08 PM
Padala Vamsi
Padala Vamsi - avatar
10 Answers
+ 7
sai vamsi Padding is only added when a structure member is followed by a member with a larger size or at the end of the structure. So it should be 1 e e e 2 2 2 2 3 e e e e e e e 4 4 4 4 4 4 4 4
19th Dec 2020, 5:25 PM
Arsenic
Arsenic - avatar
+ 6
sai vamsi this is because according to C standards, after the first member that should share an address with the struct itself, subsequent members should be at higher addresses. padding is being added for the sake of data allignment have a look here 👇 for more info on padding https://www.quora.com/What-is-structure-padding-in-C
19th Dec 2020, 3:39 PM
Arsenic
Arsenic - avatar
+ 6
You can provide a directive so that there is no padding added as follows: https://code.sololearn.com/cW6ObtyBlWsT/?ref=app
21st Dec 2020, 8:56 AM
Sonic
Sonic - avatar
+ 5
This is because compilers add padding(extra space) at the end of smaller sized variables of structure, to allign them with larger ones. It may differ from compiler to compiler as C standards state that alignment of structure totally depends on the implementation.
19th Dec 2020, 3:25 PM
Arsenic
Arsenic - avatar
+ 5
As the fourth member is 8 bytes long, it has to start at an 8-byte boundary, so the third member needs 7 bytes of padding.
21st Dec 2020, 8:53 AM
Sonic
Sonic - avatar
+ 3
let say if I print all the starting addresses of variables in structure. printf("first(%p) second(%p) third(%p) fourth(%p)\n", &node.first, &node.second, &node.three, &node.fourth); then the output is first(0x7ffc0f5f4740) second(0x7ffc0f5f4744) third(0x7ffc0f5f4748) fourth(0x7ffc0f5f4750) I understood that compiler put padding but it is not clear that where that extra 4 bytes are getting.
19th Dec 2020, 3:34 PM
Padala Vamsi
Padala Vamsi - avatar
+ 3
This is one interesting topic to discuss. I'm just reposting what my friend wrote about struct packing here, might worth to read (it's a series of posts BTW). https://www.sololearn.com/post/78037/?ref=app
19th Dec 2020, 4:06 PM
Ipang
+ 3
Thank you for the answer. Now I understood.
19th Dec 2020, 5:31 PM
Padala Vamsi
Padala Vamsi - avatar
+ 2
sorry to bother you all I am bit confused let say the alignment is e e e 1 2 2 2 2 e e e 3 4 4 4 4 4 4 4 4 where e stands for empty or padding and 1, 2, 3, 4 represents variables. Now there is only 20 bytes of memory used.
19th Dec 2020, 4:17 PM
Padala Vamsi
Padala Vamsi - avatar