Course contentsShow
← C
Lesson 1007 of 1,21914. Data Structures in CFree lesson

Array-based stack implementation

Array-based stack implementation

What you'll learn: How to use a simple array and an integer tracker to build a Last-In, First-Out (LIFO) data structure.

The cafeteria tray analogy

Imagine a stack of trays in a cafeteria. When a dishwasher adds a clean tray, they place it on the very top. When a hungry student takes a tray, they grab the one from the very top. This is LIFO: the last item added is the first one removed.

In C, we can build this using a standard array. However, an array by itself is just a row of slots. To turn it into a "Stack," we need a way to remember where the "top" is.

The "Top" variable

To implement a stack, you need two main components:

  1. The Array: A fixed-size container to hold your data.
  2. The Top Index: An integer that keeps track of the index of the last element added.

When the stack is empty, we usually set top to -1. When we add an item (Push), we increment top and place the data there. When we remove an item (Pop), we take the data at top and decrement the index.

Coding the stack

Here is how we represent this logic in code using a structure to keep the array and the tracker together:

#include <stdio.h>

#define MAX 5 // Maximum size of the stack

struct Stack {
    int items[MAX];
    int top;
};

// Initialize the stack
void initStack(struct Stack *s) {
    s->top = -1; // -1 means the stack is empty
}

// Push: Add an element to the top
void push(struct Stack *s, int value) {
    if (s->top == MAX - 1) {
        printf("Stack Overflow! Cannot add %d\n", value);
    } else {
        s->top++;
        s->items[s->top] = value;
        printf("Pushed %d\n", value);
    }
}

// Pop: Remove the top element
int pop(struct Stack *s) {
    if (s->top == -1) {
        printf("Stack Underflow! The stack is empty.\n");
        return -1;
    } else {
        int value = s->items[s->top];
        s->top--;
        return value;
    }
}

How it works

Notice that we don't actually "delete" the values in the array when we pop them. We simply move the top index down. The next time we push a value, the old data will be overwritten. The top variable acts as a gatekeeper, ensuring we only ever interact with the very last element we put in.

Key takeaway

An array-based stack uses a fixed-size array and a "top" index to ensure that the last element added is always the first one retrieved.