Why the size of structure is 24 ? why not 20 ? | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 1

Why the size of structure is 24 ? why not 20 ?

struct node{ int data; //size 4 int a; /size 4 int b; /size 4 struct node *next; //size 8 };

1st Dec 2018, 2:14 PM
sachin billav
sachin billav - avatar
7 Answers
+ 4
I think this has to do with the padding when aligning memory. I'm not so sure though. Check out C alignment.
1st Dec 2018, 2:26 PM
Bebida Roja
Bebida Roja - avatar
+ 3
The reason for the behaviour is padding. BUT if padding happens depends on the architecture and the compiler. Sololearn = 64bit system with gcc compiler has pointer size of 8 bytes (struct node* next). Now gcc does padding using the biggest member of the struct. In your case the pointer. Now data, a and b sums up to 12 bytes. Padding makes it to 16 bytes, + the 8 bytes of pointer = 24 bytes. BUT I said if padding happens depends. For example if I run your code on my 32bit system size of pointer is only 4 bytes --> and padding does not happen. The size of the structure on my system is only 16. Again node, a, b sum up to 12, + plus 4 bytes for the pointer = 16 bytes. (no padding needed).
1st Dec 2018, 8:49 PM
mimtelf
mimtelf - avatar
+ 2
Kirk Schafer as the pointer size is 8byte according to my understanding it has to be a 64bit system. Might it be that the system changed recently ?!
3rd Dec 2018, 7:09 AM
mimtelf
mimtelf - avatar
+ 1
[companion demo] In the code segment below (paste into a CodePlayground code of your own): 1. Run it. What do you observe? 2. Uncomment the char. What do you observe? 3. Increase the number of chars to 5. What happens? struct node{ int data; int a; int b; // char c[4]; // See instructions struct node *next; } n; int main() { printf("size n: %d\n", (int)sizeof(n)); printf("data: %I64d @ 0x%p (%I64d)\n", sizeof(n.data), &n.data, (size_t)&n.data); printf(" a: %I64d @ 0x%p (%I64d)\n", sizeof(n.a), &n.a, (size_t)&n.a); printf(" b: %I64d @ 0x%p (%I64d)\n", sizeof(n.b), &n.b, (size_t)&n.b); printf("next: %I64d @ 0x%p (%I64d)\n", sizeof(n.next), &n.next, (size_t)&n.next); //...
1st Dec 2018, 6:48 PM
Kirk Schafer
Kirk Schafer - avatar
+ 1
I forget where I saw this, but despite the arch (x64) I believe codes here use the 32-bit subsystem...except that pointer is 8 bytes...hmm.
3rd Dec 2018, 5:25 AM
Kirk Schafer
Kirk Schafer - avatar
+ 1
mimtelf Ah...I think I'm mixing up langs. Now that I've considered, I remember establishing in my head that Python had 32-bit addressing (here, if you get into ctypes or just id() the pointers/addresses are 4 bytes) and: I remember being surprised to see a c code that could malloc() a gigantic block without throwing an exception...that was early on for me, so I'm thinking: unchanged. ~ Apologies for the noise / mixup ~
3rd Dec 2018, 5:09 PM
Kirk Schafer
Kirk Schafer - avatar