Union vs Struct Memory Layout
C++
Hard
2 views
Problem Description
Compare memory usage of union and struct with same members.This teaches memory optimization techniques.
Logic: Use sizeof to compare memory allocation
Official Solution
void question15_union_vs_struct() {
struct MyStruct {
int a;
char b;
float c;
};
union MyUnion {
int a;
char b;
float c;
};
cout << "Struct size: " << sizeof(MyStruct) << " bytesn";
cout << "Union size: " << sizeof(MyUnion) << " bytesn";
cout << "Union uses memory of largest member!" << endl;
}
Solutions (0)
No solutions submitted yet. Be the first!
No comments yet. Start the discussion!