Members: • int i • float f
Size of structure = 8 bytes Size of union = 4 bytes Union read value = garbage / unexpected
#include <stdio.h>
// Define structure and union with same members
struct MyStruct {
int a;
float b;
char c;
};
union MyUnion {
int a;
float b;
char c;
};
int main() {
struct MyStruct s;
union MyUnion u;
// Print sizes
printf("Size of structure = %lu bytesn", sizeof(s));
printf("Size of union = %lu bytesn", sizeof(u));
// Set one member of the union
u.a = 100;
// Read other members
printf("nUnion after setting a=100:n");
printf("u.a = %dn", u.a);
printf("u.b = %fn", u.b); // reading float after int
printf("u.c = %dn", u.c); // reading char after int
return 0;
}
#include <stdio.h>
// Define structure and union with same members
struct MyStruct {
int a;
float b;
char c;
};
union MyUnion {
int a;
float b;
char c;
};
int main() {
struct MyStruct s;
union MyUnion u;
// Print sizes
printf("Size of structure = %lu bytesn", sizeof(s));
printf("Size of union = %lu bytesn", sizeof(u));
// Set one member of the union
u.a = 100;
// Read other members
printf("nUnion after setting a=100:n");
printf("u.a = %dn", u.a);
printf("u.b = %fn", u.b); // reading float after int
printf("u.c = %dn", u.c); // reading char after int
return 0;
}