Structures and Unions in C
Structs group related data into a single type. Unions share memory between members. Both are essential for modeling real-world entities and binary protocols.
Struct Basics
struct Point {
int x;
int y;
};
struct Point p = { .x = 10, .y = 20 }; /* designated initializer C99 */
printf("(%d, %d)\n", p.x, p.y);
typedef
typedef struct {
char name[64];
int age;
} Person;
Person alice = { .name = "Alice", .age = 30 };
Nested and Arrays
typedef struct {
Person owner;
struct Point vertices[4];
} Rectangle;
Unions
union Value {
int i;
float f;
char bytes[4];
};
union Value v;
v.i = 0x41424344;
/* Interpretation depends on active member — type punning via memcpy is safe */
Bit Fields
struct Flags {
unsigned int enabled : 1;
unsigned int mode : 3;
unsigned int reserved: 28;
};
/* Useful for hardware registers and compact flags */
Common Pitfalls
- Treating compiler warnings as optional rather than actionable feedback.
- Skipping error checks on library and system calls.
- Copy-pasting examples without adapting to your project’s conventions.
Best Practices
- Enable strict compiler warnings and fix them before merging.
- Write small, testable units with clear input/output contracts.
- Document non-obvious invariants and preconditions.
- Use version control and code review for every change.
Memory and Performance Notes
Struct padding aligns members to their natural boundaries. Use offsetof and sizeof to inspect layout; #pragma pack for protocol structs.
Exercise
Define a struct Date with year/month/day and a function int days_between(struct Date a, struct Date b).
Hint: Account for leap years. Consider storing dates as days since epoch internally.
Summary
Apply these concepts in small programs before moving to larger projects. Combine with adjacent topics in the learning path for deeper mastery.
Real-World Application
These concepts appear in production codebases — from operating system kernels to embedded firmware. Study open-source projects that use this topic extensively to see idiomatic patterns at scale.
Debugging Checklist
- Reproduce the issue with the smallest possible input.
- Enable compiler warnings and sanitizers.
- Use a debugger to inspect state at the failure point.
- Verify assumptions about types, sizes, and return values.
- Compare working and broken code paths side by side.
- Write a regression test once the bug is fixed.
Further Reading
Consult the ISO C standard, Effective C by Robert C. Seacord, and your compiler documentation for platform-specific behavior.
Quick Reference
Review the code examples on this page before starting the exercise. Type them manually to build muscle memory.
Additional Examples
Consider how this topic applies in a larger project:
// Break the problem into smaller functions
// Test each function independently
// Integrate incrementally
Working through variations of the examples above builds deeper understanding than reading alone.
Interview and Review Questions
- Explain the core concept of this topic in your own words.
- What happens when this code runs with edge-case input (empty, null, zero, max value)?
- How would you debug a bug related to this topic in production?
- What are the performance implications of the approach shown here?
- How does this feature compare to the equivalent in another language you know?
Related Topics in This Path
Review adjacent pages in the learning path before and after this one. Concepts build on each other — skipping ahead often leads to confusion when later pages assume mastery of earlier material.
Return to the section index if you need to fill gaps in prerequisite knowledge.