C Example Code2026-03-252 min read
Master the difference between structs and unions in C with memory layout diagrams, byte alignment, sizeof demonstrations, and working examples.
Key Differences: struct vs union
struct: Every member has its own distinct memory location. The total size is at least the sum of sizes of all members (plus padding for alignment).union: All members share the same starting memory location. The total size is equal to the size of the largest member.
Complete C Source Code
c (ISO Standard)#include <stdio.h> struct StructData { int integer; float decimal; char character; }; union UnionData { int integer; float decimal; char character; }; int main() { struct StructData s; union UnionData u; printf("Memory Size Comparison:\n"); printf(" sizeof(struct StructData) = %zu bytes\n", sizeof(struct StructData)); printf(" sizeof(union UnionData) = %zu bytes\n\n", sizeof(union UnionData)); /* Using struct: all fields retain distinct values */ s.integer = 42; s.decimal = 3.14f; s.character = 'Z'; printf("Struct Members (Independent):\n"); printf(" int: %d | float: %.2f | char: %c\n\n", s.integer, s.decimal, s.character); /* Using union: fields share the same memory location */ u.integer = 100; printf("Union after setting integer:\n"); printf(" u.integer = %d\n", u.integer); u.character = 'A'; printf("Union after setting character:\n"); printf(" u.character = %c | u.integer (corrupted) = %d\n", u.character, u.integer); return 0; }
Sample Output
text (ISO Standard)Memory Size Comparison: sizeof(struct StructData) = 12 bytes sizeof(union UnionData) = 4 bytes Struct Members (Independent): int: 42 | float: 3.14 | char: Z Union after setting integer: u.integer = 100 Union after setting character: u.character = A | u.integer (corrupted) = 65
Complexity Analysis
- Access Time:
O(1)direct offset access for both. - Memory Conservation: Unions save memory in embedded and low-level network packet header decoders.
Related Guides
- Comprehensive struct guide in Structures in C.
- Pointer access via arrow operator (
->) in Pointers in C.