+ 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.
10 Réponses
+ 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
+ 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
+ 6
You can provide a directive so that there is no padding added as follows:
https://code.sololearn.com/cW6ObtyBlWsT/?ref=app
+ 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.
+ 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.
+ 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.
+ 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
+ 3
Thank you for the answer. Now I understood.
+ 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.