C Programming

Lesson 8 of 11

Stack Data Structure

Time to combine structs and pointers into a real, reusable data structure: a stack (last-in, first-out), backed by the heap so it can grow.

C

The arrow operator

s->items is shorthand for (*s).items, "dereference the pointer s, then access the items member". Since working with pointers-to-structs is so common in C, -> exists purely to avoid writing (*s). everywhere.

Where does each piece live?

This is the key insight for this lesson: stackCreate allocates two separate heap blocks, the IntStack struct itself, and the items array it points to. They're independent allocations linked only by the pointer stored inside the struct, which is exactly why stackFree must free both, and in the right order, freeing s before s->items would leak the array's memory forever since you'd lose the only pointer to it.

C

📝 Stack Data Structure Quiz

Passing score: 70%
  1. 1.What does the -> operator do?

  2. 2.In the IntStack example, freeing the struct before freeing its items array would leak the array's memory.

  3. 3.A stack follows a "last in, first ____" ordering.