Structure vs Union Memory
C
Medium
3 views
Problem Description
Create a structure and union the same members. Do sizeof(). In the union, set one member and read the other - what do you get and why?
Official Solution
#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;
}
Solutions (0)
No solutions submitted yet. Be the first!
No comments yet. Start the discussion!