100% Free Forever
AI-Powered Learning
Industry Expert Content
Certificates & Badges
Learn At Your Own Pace

C Structs & Unions Cheat Sheet

C Structs & Unions Cheat Sheet

Explains defining and using C structs and unions, including member access, typedef, padding, bit-fields, and memory layout differences.

2 PagesBeginnerMar 22, 2026

Struct Basics

Declaring, initializing, and accessing struct members.

c
struct Point {    int x;    int y;};struct Point p1 = {10, 20};   // Aggregate initializationp1.x = 30;                    // Access member with the dot operatorstruct Point *ptr = &p1;ptr->y = 40;                  // Access member through a pointer with ->

typedef and Designated Initializers

Common patterns for naming and initializing structs.

c
typedef struct {    char name[32];    int age;} Person;Person alice = {.name = "Alice", .age = 30};  // Designated initializers (C99)Person people[3];                              // Array of structspeople[0] = alice;

Unions

Multiple members sharing the same storage.

c
union Value {    int i;    float f;    char bytes[4];};union Value v;v.i = 65;              // Only one member is valid at a timeprintf("%d\n", v.i);v.f = 3.14f;           // Overwrites v.i; the same memory is reusedprintf("%f\n", v.f);

Struct vs Union

Key differences in layout and sizing.

  • struct- Each member has its own storage; total size >= sum of member sizes plus padding
  • union- All members share the same storage; size equals the size of the largest member
  • Padding- The compiler may insert padding bytes between members for alignment
  • sizeof- Use sizeof(struct T) to get the actual allocated size, including padding
  • Self-referential structs- A struct can contain a pointer to its own type, enabling linked lists and trees
  • Bit-fields- struct Flags { unsigned int a: 1; unsigned int b: 3; }; packs fields into fewer bits
  • Anonymous unions- C11 allows a union to be embedded in a struct without a member name
Pro Tip

When passing a struct to a function, the entire struct is copied by value — pass a pointer (const struct Point *) for large structs to avoid the copy overhead.

Was this cheat sheet helpful?

Explore Topics

#CStructsUnions#CStructsUnionsCheatSheet#Programming#Beginner#StructBasics#TypedefAndDesignatedInitializers#Unions#StructVsUnion#CheatSheet#SkillVeris