

0 / 2 embers
0 / 3000 xp
click for more info
Complete a lesson to start your streak
click for more info
Difficulty: 6
click for more info
Not enough gems
Cost: 6 gems
1: Union
incomplete
2: Memory Layout
incomplete
3: Union Size
incomplete
4: Helper Fields
incomplete
This lesson's interactive features are locked, please to keep using them
A downside of unions is that the size of the union is the size of the largest field in the union. Take this example:
typedef union IntOrErrMessage {
int data;
char err[256];
} int_or_err_message_t;
This IntOrErrMessage union is designed to hold an int 99% of the time. However, when the program encounters an error, instead of storing an integer here, it will store an error message. The trouble is that it's incredibly inefficient because it allocates 256 bytes for every int that it stores!
Imagine an array of 1000 int_or_err_message_t objects. Even if none of them make use of the .err field, the array will take up 256 * 1000 = 256,000 bytes of memory! An array of ints would have only taken 4,000 bytes (assuming 32-bit integers).
Assume the following:
sizeof(int) = 4sizeof(char) = 1sizeof(long int) = 8union SensorData {
long int temperature;
long int humidity;
long int pressure;
};
union PacketPayload {
char text[256];
unsigned char binary[256];
struct ImageData {
int width;
int height;
unsigned char data[1024];
} image;
};
union Item {
struct {
int damage;
int range;
int size;
} weapon;
struct {
int healingAmount;
int duration;
} potion;
struct {
int doorID;
} key;
};