+ 3

I didn't understand this code

union abc{ char a,b,c,d,e,f,g,h; int i; }abc; int main(){ printf("%d",sizeof(abc)); return 0; } Output given is 4 .. but how??

2nd Apr 2020, 9:13 PM
Pooja Soni
Pooja Soni - avatar
4 odpowiedzi
+ 1
Output is sizeof int 4bytes. For the union, storage is allocated is the bigest size of type in that union... There char type requires only 1bytes and int requires 4bytes. So biggest is 4bytes is alloted by that union. And each time only one type value is stored of that unoin value, by most recent calculations on that union values. If you add double type then you get output as 8.
2nd Apr 2020, 9:29 PM
Jayakrishna 🇮🇳
+ 2
union, storage is allocated the bigest size of type . There char type requires only 1bytes and int allocate 4bytes. So biggest is 4bytes is alloted by that uniton I
4th Apr 2020, 6:59 PM
A S Raghuvanshi
A S Raghuvanshi - avatar
+ 1
It depends on the alignment that the compiler puts into the allocated space. So, unless you use some special option, the compiler will put padding into your union space.
2nd Apr 2020, 9:29 PM
Nicholas Falcone
Nicholas Falcone - avatar
0
Output is sizeof int 4bytes. For the union, storage is allocated is the bigest size of type in that union... There char type requires only 1bytes and int requires 4bytes. So biggest is 4bytes is alloted by that union. And each time only one type value is stored of that unoin value, by most recent calculations on that union values. If you add double type then you get output as 8.
4th Apr 2020, 6:04 AM
Prasad Lotke
Prasad Lotke - avatar