C Programming • C17 baseline, standards-specific features labeled
Build a Small Stack with an Array
Combine arrays, bounds, and functions to create a fixed-capacity last-in-first-out stack.
A stack supports adding an item at the top and removing the most recently added item. The count is also the next free index, so push must check capacity before writing and pop must check that the stack is not empty.
Example
#include <stdbool.h>
#include <stddef.h>
#define STACK_CAPACITY 16
struct stack {
int items[STACK_CAPACITY];
size_t count;
};
bool push(struct stack *stack, int value) {
if (stack == NULL || stack->count == STACK_CAPACITY) {
return false;
}
stack->items[stack->count++] = value;
return true;
}
What to expect
push returns false for a null stack or a full stack, and true after storing an item.
Key idea: State capacity and empty/full behavior in the API, then test both boundary conditions.