A union in C is a special user-defined data type where all members share the exact same memory location. Unlike a struct which allocates cumulative memory for every field, a union takes only as much memory as its single largest member.
Union vs Struct Memory Allocation Comparison
#include <stdio.h>
union DataPayload {
int i;
float f;
char str[20];
};
struct DataStruct {
int i;
float f;
char str[20];
};
int main(void) {
union DataPayload payload;
// Writing to int member
payload.i = 100;
printf("payload.i: %d\n", payload.i);
// Overwriting shared memory with string
snprintf(payload.str, sizeof(payload.str), "Lynxbee");
printf("payload.str: %s\n", payload.str);
printf("sizeof(union DataPayload): %zu bytes\n", sizeof(union DataPayload)); // 20 bytes
printf("sizeof(struct DataStruct): %zu bytes\n", sizeof(struct DataStruct)); // 28 bytes (with alignment padding)
return 0;
}
Comments and corrections