0

Union

I declared an union structur with 3 different type of datatypes. All of the members are initialized and as an output I'm getting 8 Bytes. Why I'm getting 8 Bytes? union info { int a;//4Bytes float b;//4Bytes char c[5];//5Bytes }; int main() { union info i; i.a=4; i.b=3.4; strcpy(i.c,"David"); printf("Gesamtspeicherplatz: %d Bytes\n",sizeof(i));

8th Aug 2019, 8:41 AM
Preet
3 Réponses
+ 6
When you write at int and read the float you get a broken number as output because it literally shares the same memory location, thus, float contains the int and some garbage.
8th Aug 2019, 8:45 AM
Valen.H. ~
Valen.H. ~ - avatar
+ 4
A structs size is determined by the biggest datatype/bitfield it contains
8th Aug 2019, 8:44 AM
Valen.H. ~
Valen.H. ~ - avatar
+ 4
This is a float that conditionally stores an int or 5 chars
8th Aug 2019, 8:44 AM
Valen.H. ~
Valen.H. ~ - avatar