Building a Stack in C with an Array

UNIT 2 • MODULE 1 • LESSON 03

In Lesson 02 you met the stack as an idea: a pile where the last item in is the first item out, with Push, Pop, Empty and Full as its operations. You traced stacks on paper and wrote the algorithms in pseudocode. In this lesson you turn those algorithms into working C code that compiles, runs and protects itself from overflow and underflow.

Examiners love this topic because it joins two parts of the course: data structures from Unit 2 and C programming from Unit 1. A typical Paper 02 question asks you to explain how a stack is implemented, declare the variables it needs, then write push and pop functions in C that handle overflow and underflow. By the end of this lesson you will be able to do all of that from memory, and you will know the small bugs that cost marks.

What you will learn

  • How a stack is implemented with a one-dimensional array and an integer top.
  • How to declare the variables a stack needs, including a character stack.
  • How to write isEmpty, isFull, push, pop and peek in C, catering for overflow and underflow.
  • How to package a stack in a struct and pass it by pointer, so one program can use several stacks.
  • How to build a simple menu-driven stack program and test it with boundary cases.
  • The classic C stack bugs, and how to spot and fix them.

Part 1: From pseudocode to C

Start from the algorithm, not the code. Here is the stack you know from Lesson 02, written once more in pseudocode. Every line below has a direct partner in C, so keep this beside you as you read the C version.

CONSTANT MAX ← 5
DECLARE stack : ARRAY[0 : MAX - 1] OF INTEGER
DECLARE top : INTEGER
top ← -1

PROCEDURE push(item)
    IF top = MAX - 1 THEN
        OUTPUT "Overflow"
    ELSE
        top ← top + 1
        stack[top] ← item
    ENDIF
END PROCEDURE

FUNCTION pop()
    IF top = -1 THEN
        OUTPUT "Underflow"
        RETURN a signal value
    ELSE
        item ← stack[top]
        top ← top - 1
        RETURN item
    ENDIF
END FUNCTION

Now match each idea to C:

Pseudocode ideaC version (and why)
CONSTANT MAX ← 5#define MAX 5 gives one place to change the capacity.
ARRAY[0 : MAX – 1]int stack[MAX]; because C arrays always start at index 0.
top ← -1int top = -1; as nothing is stored yet.
top = MAX – 1top == MAX - 1 using == to compare, not =.
top ← top + 1top++; moves up to the free slot.
top ← top – 1top--; moves down after reading.
OUTPUT “Overflow”printf("Overflow\n"); reports the error; then leave the function.

Two small things trip students up. First, in C a single = assigns and a double == compares. Writing if (top = MAX - 1) silently sets top to MAX – 1 and is almost always true, so your stack would claim to be full forever. Second, a function that reports an error must also stop. Printing “Overflow” and then carrying on to top++ still writes past the end of the array. Use return straight after the message, or put the normal work in an else.

Part 2: The exam-style character stack

A favourite exam scenario is a stack of characters with a fixed size such as 1000, where top is a global variable. “Declare the variables” means exactly three things: the size, the array and the top tracker.

#define SIZE 1000      /* capacity */
char stack[SIZE];      /* the storage */
int top = -1;          /* empty to start */

Because stack and top are global, every function can see them without parameters. That keeps exam answers short, but it also means the program can only ever have one stack. You will fix that limitation in Part 4.

Worked example 1: push and pop for characters

This program pushes the four letters of a word, pops them all (reversing the word, as you saw in Lesson 02), and then pops once more to show underflow being caught. Notice how pop returns the null character '\0' as a signal value when there is nothing to return.

#include <stdio.h>

#define SIZE 1000

char stack[SIZE];
int top = -1;

void push(char ch)
{
    if (top == SIZE - 1) {
        printf("Overflow: %c lost\n", ch);
        return;
    }
    top++;
    stack[top] = ch;
}

char pop(void)
{
    char ch;
    if (top == -1) {
        printf("Underflow: stack empty\n");
        return '\0';
    }
    ch = stack[top];
    top--;
    return ch;
}

int main(void)
{
    const char *word = "EXAM";
    int i;

    for (i = 0; word[i] != '\0'; i++)
        push(word[i]);
    printf("Pushed %d chars, top = %d\n",
           i, top);
    printf("Popped: ");
    while (top != -1)
        printf("%c", pop());
    printf("\ntop is back to %d\n", top);
    pop();
    return 0;
}

Output:

Pushed 4 chars, top = 3
Popped: MAXE
top is back to -1
Underflow: stack empty

Walk through it. Each push checks the full condition (top == SIZE - 1) first. Only when there is room does it move top up and store the character. After four pushes, top is 3, because the letters sit at indexes 0, 1, 2 and 3. Pop does the mirror image: it checks the empty condition (top == -1), copies stack[top] into a local variable, moves top down and returns the copy. The final pop finds top at -1, prints the underflow message and returns without touching the array.

Why copy into a local variable first? You cannot write return stack[top]; top--; because nothing after a return runs. You also cannot write top--; return stack[top];, which returns the wrong item. Copy, move, return: that order always works. (A compact alternative is return stack[top--];, which reads first and then decrements, but the three-line version is clearer to examiners and easier to debug.)

Part 3: Spot the bug

Most lost marks on stack questions come from a handful of small mistakes: an off-by-one full test, steps in the wrong order, or a struct passed by value. The next Try it gives you six short C fragments. Each has exactly one faulty line. Tap the line you think is wrong to see why and how to fix it.

Try it 1Spot the bug in C stack code

Six short stack functions, each with one bug. Tap the faulty line. Use Next program to move on.

If you found all six, you now have a checklist to use on your own code: the full test uses MAX - 1; the empty test uses -1; push moves then stores; pop reads then moves; every error path returns; and any function that changes a struct receives its address.

Part 4: A reusable stack using a struct

Global variables are fine for a single stack, but real programs often need two or more: an Undo stack and a Redo stack, or one stack per player in a game. The neat solution is to bundle the array and its top into a structure, then write the operations once and pass each one the address of the stack it should work on. You met structs and pointers in Unit 1; here they come together.

TYPE Stack
    items : ARRAY[0 : MAX - 1] OF INTEGER
    top   : INTEGER
END TYPE

FUNCTION push(BYREF s : Stack, item)
         RETURNS BOOLEAN
    IF s.top = MAX - 1 THEN
        RETURN FALSE
    ENDIF
    s.top ← s.top + 1
    s.items[s.top] ← item
    RETURN TRUE
END FUNCTION

In C, "by reference" means passing a pointer. Inside the function you use the arrow operator: s->top means "the top field of the struct that s points to". Returning 1 for success and 0 for failure lets the caller decide what to print, which makes the functions more reusable than ones that print their own messages.

Worked example 2: two stacks, one set of functions

#include <stdio.h>

#define MAX 3

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

void init(Stack *s)
{
    s->top = -1;
}

int isEmpty(const Stack *s)
{
    return s->top == -1;
}

int isFull(const Stack *s)
{
    return s->top == MAX - 1;
}

int push(Stack *s, int item)
{
    if (isFull(s))
        return 0;
    s->top++;
    s->items[s->top] = item;
    return 1;
}

int pop(Stack *s, int *item)
{
    if (isEmpty(s))
        return 0;
    *item = s->items[s->top];
    s->top--;
    return 1;
}

int main(void)
{
    Stack a, b;
    int v, i;

    init(&a);
    init(&b);
    for (i = 1; i <= 4; i++) {
        if (push(&a, i * 10))
            printf("A: pushed %d\n",
                   i * 10);
        else
            printf("A: full, %d refused\n",
                   i * 10);
    }
    while (pop(&a, &v)) {
        push(&b, v);
        printf("Moved %d from A to B\n", v);
    }
    if (!pop(&a, &v))
        printf("A: empty, pop refused\n");
    if (pop(&b, &v))
        printf("Top of B was %d\n", v);
    return 0;
}

Output:

A: pushed 10
A: pushed 20
A: pushed 30
A: full, 40 refused
Moved 30 from A to B
Moved 20 from A to B
Moved 10 from A to B
A: empty, pop refused
Top of B was 10

Stack a has room for three items, so the fourth push returns 0 and main prints the refusal. The while (pop(&a, &v)) loop is a common pattern: it keeps popping until pop reports failure. Each value popped from A is pushed onto B, which reverses the order, so 10 (pushed first onto A) ends up on top of B. Notice that pop hands its value back through the pointer parameter int *item. This avoids needing a special "signal value", which matters when every integer could be valid data.

Step through a shorter version of this program, and a tiny character stack, in the tracer below. Predict each result before you reveal it.

Try it 2Trace C stack programs

Choose a program, then step through it. Answer each question before moving on.

Output


Part 5: A menu-driven stack program

School-Based Assessment projects and many exam questions ask for a menu so a user can push, pop, peek and display items. The program below reads menu choices (1 push, 2 pop, 3 peek, 4 show, 0 quit) from the keyboard. To make the output easy to follow, it echoes each command before showing the stack from bottom to top.

#include <stdio.h>

#define MAX 3

int stack[MAX];
int top = -1;

void show(void)
{
    int i;
    if (top == -1) {
        printf("  (empty)\n");
        return;
    }
    printf("  bottom:");
    for (i = 0; i <= top; i++)
        printf(" %d", stack[i]);
    printf(" :top\n");
}

int main(void)
{
    int choice = -1, item;

    while (scanf("%d", &choice) == 1) {
        if (choice == 0)
            break;
        if (choice == 1) {
            if (scanf("%d", &item) != 1)
                break;
            printf("> push %d\n", item);
            if (top == MAX - 1) {
                printf("  Overflow\n");
                continue;
            }
            top++;
            stack[top] = item;
        } else if (choice == 2) {
            printf("> pop\n");
            if (top == -1) {
                printf("  Underflow\n");
                continue;
            }
            printf("  got %d\n",
                   stack[top]);
            top--;
        } else if (choice == 3) {
            printf("> peek\n");
            if (top == -1)
                printf("  Nothing\n");
            else
                printf("  top item %d\n",
                       stack[top]);
        } else {
            printf("> show\n");
        }
        show();
    }
    printf("Bye\n");
    return 0;
}

Sample input: 2 1 5 1 8 3 1 2 1 9 2 4 0

Output:

> pop
  Underflow
> push 5
  bottom: 5 :top
> push 8
  bottom: 5 8 :top
> peek
  top item 8
  bottom: 5 8 :top
> push 2
  bottom: 5 8 2 :top
> push 9
  Overflow
> pop
  got 2
  bottom: 5 8 :top
> show
  bottom: 5 8 :top
Bye

Look at how the sample input was chosen. It starts with a pop on an empty stack (underflow), fills the stack exactly to capacity (5, 8, 2), tries one more push (overflow), then pops and shows. That is a deliberate test plan. When you test any data structure, always include:

Test caseExample inputExpected result
Pop or peek on an empty stackpop firstUnderflow message; program keeps running
Normal pushpush 55 appears at the bottom
Fill exactly to capacitythree pushes when MAX = 3All accepted; top = MAX - 1
Push when fulla fourth pushOverflow message; contents unchanged
Pop after fullpopReturns the last item pushed (LIFO)
Pop until empty, then once morerepeat popUnderflow is caught again

Notice also how show loops from index 0 up to top, not up to MAX - 1. Slots above top may still hold old values from earlier pushes, but they are not part of the stack. Printing them would make a popped item appear to come back.

Part 6: Variations you should recognise

The array version above is the standard one for CAPE, but you should be able to recognise and explain a few variations:

  • 1-based stacks: some pseudocode numbers slots 1 to MAX. Then empty is top = 0, full is top = MAX, and push still moves top first. In C you can imitate this by declaring MAX + 1 slots and ignoring index 0, but the 0-based version is more natural.
  • top points to the next free slot: some implementations start top = 0 and store first (stack[top] = item; top++;), then pop decrements first. This is correct as long as every function uses the same meaning. Mixing the two meanings is exactly bug 2 in the Try it.
  • Stacks of records: the items array can hold structs, such as Student items[MAX];, so a stack can store whole records, not just numbers or characters.
  • Linked stacks: instead of an array, each item can sit in a node that links to the item below it. There is then no fixed capacity, so no overflow until memory runs out. You will meet linked structures in Lesson 06.

Whatever the variation, an examiner will look for the same four features: storage for the items, a way to know where the top is, a check before adding (overflow) and a check before removing (underflow).

Explaining the implementation in words

When a question asks you to explain how a stack is implemented, a strong answer covers storage, the top indicator and the operations. For example: "A stack can be built from a one-dimensional array of fixed size together with an integer variable top that holds the index of the most recently added item. top starts at -1 to show the stack is empty. To push, the program checks that top is less than the last index, increases top by one and stores the new item at that index. To pop, it checks that top is not -1, copies the item at index top, then decreases top by one. Because items are only ever added and removed at index top, the structure behaves as last in, first out." Write it in your own words, but make sure each of those points appears.

Try it 3C stack drill

Pick a mode. "Numbers" asks what top or the item count is after a run of C calls. "Rules" checks the C details that earn marks.

Summary

IdeaRemember
Declarations#define MAX, an array of MAX items, int top = -1.
isEmpty / isFulltop == -1 and top == MAX - 1.
pushIf full, report overflow and return. Otherwise top++, then store.
popIf empty, report underflow and return a signal. Otherwise copy stack[top], top--, return the copy.
Struct stackBundle items and top; pass Stack * and use the arrow operator.
TestingEmpty pop, fill to capacity, push when full, pop until empty.

Review questions

1. Write C declarations for a stack that can hold 500 integers, with top as a global variable, starting empty.

Show answer

#define MAX 500
int stack[MAX];
int top = -1;

2. Write a C function push(int item) for the stack above that caters for overflow.

Show answer

void push(int item)
{
if (top == MAX - 1) {
printf("Overflow\n");
return;
}
top++;
stack[top] = item;
}

3. Write a C function pop() that returns the top integer and caters for underflow by returning -1.

Show answer

int pop(void)
{
int item;
if (top == -1) {
printf("Underflow\n");
return -1;
}
item = stack[top];
top--;
return item;
}

4. Why is returning -1 from pop a weakness for an integer stack? Suggest an improvement.

Show answer

Because -1 might be a genuine item, the caller cannot tell an error from real data. Better: return a success flag (1 or 0) and pass the popped value back through a pointer parameter, as in struct_stack.c.

5. Explain why a function that pushes onto a struct stack must take a Stack * parameter.

Show answer

C passes arguments by value. With a plain Stack parameter the function changes a local copy, so the caller’s stack never changes. Passing the address lets the function change the original.

6. A student writes stack[top] = item; before top++; in push, starting from top = -1. What goes wrong?

Show answer

The first push writes to stack[-1], which is outside the array, and every later item is stored one slot lower than top says. Data is corrupted and the top item can be lost.

7. What will the show function print after: push 4, push 7, pop, push 9 (MAX = 3)? Why does 7 not appear?

Show answer

bottom: 4 9 :top. After the pop, top moved down, and the push of 9 overwrote slot 1. Show only prints indexes 0 to top.

8. List four test cases you would use to check a stack program.

Show answer

Pop on an empty stack; push until exactly full; push once more when full; pop until empty then pop again (plus normal push and pop in between).

Homework

  1. Write a complete C program with a global char stack of size 1000 and functions push(char) and pop() that cater for overflow and underflow. Use it to print any word backwards.
  2. Add a peek function to struct_stack.c that returns 1 and passes back the top value without changing top, or returns 0 if the stack is empty.
  3. Extend the menu program with option 5, which prints how many items are on the stack (hint: top + 1).
  4. Write a function that uses a stack to check whether a word typed by the user is a palindrome.
  5. Rewrite push and pop for the "top points to the next free slot" convention (top starts at 0). Test them with the same test plan.

Mastery quiz: Stacks in C

This 10-question quiz is separate from the short Quick quiz at the end of the lesson. Score 8/10 or higher to earn this lesson’s badge. Your best score is saved in this browser on this device.

Mastery quiz: Building a Stack in C with an Array

Your course badges: loading saved progress…

View badges

    No course badges earned yet. Score 8/10 in a lesson quiz to earn its badge.

    Saved in this browser on this device. Clearing browser data may remove your badges.

    Answer all 10 questions. Earn this lesson’s badge at 8/10 or higher. Read the explanations, revisit the Try it activities and retry as often as you need. These are self-study badges, not formal grades.

    1. Which declaration creates an empty 0-based stack of 100 integers?
    2. In push, which order is correct after the full check?
    3. In pop, which order is correct after the empty check?
    4. The full test for a stack of SIZE items (0-based) is...
    5. Why should an error branch in push end with return?
    6. Inside void push(Stack *s, int item), how do you increase top?
    7. Why pass a Stack by pointer?
    8. A display function should print stack items from index 0 up to...
    9. MAX is 3. After push 1, push 2, push 3, push 4, pop, what is returned by the pop?
    10. Which is the best way for an integer pop to report underflow without clashing with real data?

    Exam tips

    Specimen Unit 2 Paper 02 (2021), Question 1. Part (a) asks you to explain how a stack is implemented; use the paragraph model in Part 6 (array, top, LIFO, push and pop with checks). Part (b) uses a character stack with a global top: declare the size, the char array and top; then write push with an overflow check and pop with an underflow check. Marks go to the check, the correct order of steps, and the return. Write tidy, indented C, and state your convention (top starts at -1) in a comment.

    Paper 01 stack items. When an item shows a sequence such as initialise, push, push, pop, push, push, pop, draw the array and move top step by step. Do not erase popped values in your head; just move top. Then read the stack from index 0 to top.

    Common slips. Using = instead of == in a test; testing top == MAX; forgetting return after an error; writing to stack[top] before moving top; and losing the popped value by decrementing first.

    More worked answers are on the CS Solutions page.

    Previous: Unit 2 • Module 1 • Lesson 02 – Stacks: LIFO, Push, Pop, Empty and Full (Diagrams and Algorithms). Next: Unit 2 • Module 1 • Lesson 04 – Queues: FIFO, Enqueue, Dequeue and Linear Queues in C.

    Syllabus link: CAPE Computer Science (CXC A19/U2/21), Data Structures (Unit 2, Module 1). Specific Objective 4: write programs to implement standard ADTs (stacks using a one-dimensional array in C).

    Video search terms

    Search YouTube for: "stack implementation in C using array", "push pop function C overflow underflow", "stack using struct in C".

    Try it 4Quick quiz

    Tap an answer. All eight questions are self-checks on this lesson.

    Updates

    2026/12/01

    - First version of the lesson.

    © 2026 islandclass.org

    Leave a Reply