Stack Array Implementation in C

Intermediate
6 min read
Updated: Nov 2026
1 example

Stack Backed by an Array

An array stack keeps items in data[0..top]. It is the simplest and fastest implementation: no allocation, good cache behavior, O(1) operations. The cost is a fixed capacity, so push must check for full. For a growable stack, allocate the array dynamically and realloc when full.

Remember
#define CAP 3
struct Stack { int data[CAP]; int top; };
if (s->top == CAP - 1) { /* full */ }

Cheat Sheet

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

TopicDetail
CapacityFixed at compile time
Fulltop == CAP - 1
Emptytop == -1
Growthrealloc for dynamic arrays

C Examples

Compile each example with gcc file.c -std=c11 -Wall -o out. Next: Stack Linked List Implementation in C.

Example 1 — Fill the stack until it is full

Capacity 3, four pushes.

C
#include <stdio.h>
#define CAP 3

struct Stack { int data[CAP]; int top; };

static int push(struct Stack *s, int v) {
    if (s->top == CAP - 1) return 0;
    s->data[++s->top] = v;
    return 1;
}

int main(void) {
    struct Stack s = {{0}, -1};

    for (int i = 1; i <= 4; i++) {
        if (push(&s, i)) printf("pushed %d\n", i);
        else printf("stack full, %d rejected\n", i);
    }
    printf("top=%d\n", s.data[s.top]);
    return 0;
}

How It Works

  1. Three pushes fill indexes 0 to 2.
  2. The fourth push is refused instead of overrunning the array.
  3. The top is still 3 afterwards.

Edge Cases & Pitfalls

Check these before relying on Stack Array Implementation in C in real programs.

bound

No full check

Writing data[CAP] is out of bounds.

macro

Magic numbers

Use the CAP macro in both the array and the check.

Key Takeaways

  • Simple and fast.
  • Fixed capacity.
  • Check full before push.

One line: An array stack keeps items in data[0..top].

Frequently Asked Questions

Keep an array and an integer top index starting at -1. Push increments top then stores; pop reads then decrements.
Allocate with malloc and use realloc to double the capacity when top reaches the end.
Continue with "Stack Linked List Implementation in C" next. Push and pop at the head of a singly linked list. The C Stacks hub lists every topic in order.

Next: Stack Linked List Implementation in C

Push and pop at the head of a singly linked list.

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.

10 people found this page helpful