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

The Push operation

The Push operation

What you'll learn: How to add a new element to the top of a stack using the "Push" operation.

In the world of data structures, a Stack follows the Last-In, First-Out (LIFO) principle. Think of a physical stack of cafeteria trays. When you bring a new tray to the stack, you don't crawl under the table to put it at the bottom, and you don't wedge it into the middle. You simply place it right on top. In C programming, this action is called a Push.

How Pushing Works

When you push an item onto a stack, two specific things happen behind the scenes:

  1. The Pointer Moves: The "top" index (which keeps track of where the highest item is) increases by one to make room for the new arrival.
  2. The Data is Placed: The new value is written into that newly created space at the top.

Imagine a stack implemented using an array. If the stack is currently empty, our "top" marker might be at -1. When we push our first number, we move the marker to 0 and store the number there. If we push again, the marker moves to 1, and so on.

Coding the Push

To perform a push in C, we usually use a struct to hold our array and a variable representing the top index. Before we add data, we must always check if the stack is full to prevent a "Stack Overflow" error.

#include <stdio.h>

#define MAX 5 // Maximum size of the stack

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

void push(struct Stack *s, int value) {
    // 1. Check if there is space left
    if (s->top == MAX - 1) {
        printf("Stack Overflow! Cannot add %d\n", value);
    } else {
        // 2. Increment the top index
        s->top++;
        // 3. Insert the new value at the new top position
        s->items[s->top] = value;
        printf("Pushed %d onto the stack.\n", value);
    }
}

int main() {
    struct Stack myStack;
    myStack.top = -1; // Initialize stack as empty

    push(&myStack, 10);
    push(&myStack, 20);
    
    return 0;
}

Safety First

The most critical part of a Push operation is the boundary check. Because C doesn't automatically stop you from writing data past the end of an array, the if (s->top == MAX - 1) check is your safety net. Without it, pushing too many items would corrupt your memory, much like trying to add a tray to a stack that has already hit the ceiling.

Key takeaway

Pushing is the act of incrementing the stack's top pointer and placing a new element at that highest position.