Data Structures In C

Design clean, efficient data models. Understand memory alignment, padding, unions, and enumerations to represent complex real-world entities.

Struct Basics

Grouping related variables into a single unit.

student.c
struct Student { char name[50]; int id; float gpa; }; int main() { struct Student s1; s1.id = 101; s1.gpa = 3.8; }

Typedef

Cleaner syntax without 'struct' keyword.

typedef struct { int x, y; } Point; Point p1; // No 'struct' needed

Passing to Functions

Pass by value copies data. Pass by reference is faster.

void print(Point p); // Copy void modify(Point *p); // Reference

Memory Layout

Padding and Alignment. Why structs are larger than you think.

padding.c
struct Example { char c; // 1 byte int i; // 4 bytes }; // Size is NOT 5 bytes! It is 8 bytes. // [c] [padding:3] [i:4]
Optimization Tip: Order members from largest to smallest to minimize padding wastage.
double > int > short > char

Unions

Shared memory space. Only one member active at a time.

union Data { int i; float f; char str[20]; }; union Data data; data.i = 10; data.f = 220.5; // Overwrites i!

Enumerations

Named integer constants for readability.

enum Status { PENDING = 0, RUNNING = 1, DONE = 2 }; enum Status s = RUNNING;