A tidy stack wraps its array and top index in a struct and exposes small functions: push, pop, peek, is_empty, is_full, and size. Operations that can fail return a status so callers can react. All core operations run in O(1) time.
Remember
struct Stack { int data[4]; int top; };
int push(struct Stack *s, int v);
int pop(struct Stack *s, int *out);
int peek(const struct Stack *s, int *out);
int is_empty(const struct Stack *s);
Reference
Cheat Sheet
Keep these facts handy while you work with Stack Operations in C.
#include <stdio.h>
struct Stack { int data[4]; int top; };
static int is_empty(const struct Stack *s) { return s->top < 0; }
static int push(struct Stack *s, int v) {
if (s->top == 3) return 0;
s->data[++s->top] = v;
return 1;
}
static int pop(struct Stack *s, int *out) {
if (is_empty(s)) return 0;
*out = s->data[s->top--];
return 1;
}
int main(void) {
struct Stack s = {{0}, -1};
int v;
push(&s, 1); push(&s, 2); push(&s, 3);
printf("size=%d top=%d\n", s.top + 1, s.data[s.top]);
pop(&s, &v); printf("popped %d\n", v);
pop(&s, &v); printf("popped %d\n", v);
printf("empty? %d\n", is_empty(&s));
return 0;
}
Output
size=3 top=3
popped 3
popped 2
empty? 0
How It Works
The struct keeps the data and the top index together.
pop returns the value through an output pointer so the return value can be a status.
One item (1) remains, so the stack is not empty.
Edge Cases & Pitfalls
Check these before relying on Stack Operations in real programs.
status
Ignoring return codes
If you ignore the status, you may use an uninitialized v.
init
Starting top at 0
With top as an index, start at -1.
Remember
Key Takeaways
All O(1).
Return status codes.
Wrap state in a struct.
One line: A tidy stack wraps its array and top index in a struct and exposes small functions: push, pop, peek, is_empty, is_full, and size.
Frequently Asked Questions
Push (add), pop (remove), peek (read the top), is-empty, and size.
O(1) for push, pop, and peek in both array and linked implementations.
Continue with "Stack Array Implementation in C" next. Build a fixed-capacity stack on an array with a capacity macro. The C Stacks hub lists every topic in order.