Size of a structure | Sololearn: Learn to code for FREE!
Neuer Kurs! Jeder Programmierer sollte generative KI lernen!
Kostenlose Lektion ausprobieren
+ 2

Size of a structure

In the below code why does it print 8 ? https://code.sololearn.com/cSOyVoLKZxa3/?ref=app

21st Jul 2020, 8:54 AM
Gauri Shirkande
Gauri Shirkande - avatar
2 Antworten
+ 3
The compiler allocates memory in multiples of the size needed by 1 T where T is any type (int, char etc.). So even if you limit the size of integer fields and your struct needs just 10 bits, the compiler will still allocate memory in multiples of 4 (the size of 1 int) Consider the following struct bits{ int bit1:1; }; Although the field bit1 can occupy only 1 bit, the size of the struct still will be 4 bytes, because, as said above, it will occupy a size which is a multiple of 1 T, in this case int. Add another field to the struct, int bit2:2; the total size of needed by the struct now is just 1+2=3 bits. As 3 bits can fit in 32 bits, no new space will be assigned. Then you add another field int bit30: 30; The space needed by bit30 is 30 bits. So now the total space needed by the struct is 30+1+2 = 33 bits, i.e 4 bytes and 1 bit. Again, the compiler allocates space in multiples of 4 (size of 1 int) and thus cannot allocate 1 bit. So it will assign 4 bytes for just that 1 bit. Total size: 4+4 = 8 bytes
21st Jul 2020, 9:59 AM
XXX
XXX - avatar
+ 3
Great explanation!! Thanks a lot!🙌
21st Jul 2020, 10:04 AM
Gauri Shirkande
Gauri Shirkande - avatar