C Stack Basics

Intermediate
6 min read
Updated: Nov 2026
1 example

Last In, First Out

A stack models a pile of plates: you add and take from the top. Because the last item pushed is the first popped, a stack reverses sequences. This is why stacks are central to recursion (the call stack), undo, and parsing.

Remember
push(x);   /* add to top        */
pop();     /* remove from top   */
peek();    /* read top, no remove */

Cheat Sheet

Keep these facts handy while you work with Stack Basics in C.

TopicDetail
LIFOLast in, first out
PushAdd on top
PopRemove from top
PeekRead the top

C Examples

Compile each example with gcc file.c -std=c11 -Wall -o out. Next: Stack Operations.

Example 1 — Reverse a string with a stack

Push each character, then pop them all.

C
#include <stdio.h>
#include <string.h>

int main(void) {
    const char *s = "hello";
    char stack[16];
    int top = -1;

    for (size_t i = 0; i < strlen(s); i++) stack[++top] = s[i];

    printf("reversed: ");
    while (top >= 0) putchar(stack[top--]);
    printf("\n");
    return 0;
}

How It Works

  1. Characters are pushed h, e, l, l, o.
  2. Popping returns o first and h last.
  3. The stack reversed the order automatically.

Edge Cases & Pitfalls

Check these before relying on Stack Basics in real programs.

cap

Fixed buffer size

A 16-character stack overflows on longer input. Check lengths.

str

Forgetting the terminator

Popped characters are printed with putchar, so no \0 is needed.

Key Takeaways

  • Last in, first out.
  • Reverses order.
  • One open end.

One line: A stack models a pile of plates: you add and take from the top.

Frequently Asked Questions

Last In, First Out: the most recently added element is the first one removed.
Items are removed in the opposite order they were added.
Continue with "C Stack Operations" next. Implement push, pop, peek, is-empty, and size with a struct. The C Stacks hub lists every topic in order.

Next: Stack Operations

Implement push, pop, peek, is-empty, and size with a struct.

Continue →

CODETOFUN NEWS

Stay Ahead in Tech

Get the latest IT news, programming updates, and technology trends directly on your phone.

Your daily dose of tech, straight to your feed.

About the author

Mari Selvan M P
Mari Selvan M P 🔗

Developer, cloud engineer, and technical writer

  • Experience 12 years building web and cloud systems
  • Focus Full Stack Development, AWS, and Developer Education

I write practical tutorials so students and working developers can learn by doing—from databases and APIs to deployment on AWS.

8 people found this page helpful