Stack Data Structure in C

I am tutoring Python and Java and wanted the students to appreciate the data structures that are implemented in higher-level languages. I showed them what it takes to create a simple Stack data structure in C using an array. Coded live from scratch. Point made :)

stack.h

#ifndef STACK_H
#define STACK_H

typedef int stackElement;

typedef struct {
    int capacity;
    int top;
    stackElement *arr;
} Stack;

Stack *createStack(int capacity);
void destroyStack(Stack *stack);
void push(Stack *stack, stackElement el);
stackElement pop(Stack *stack);
stackElement peek(Stack *stack);
int capacity(Stack *stack);
int size(Stack *stack);
int isFull(Stack *stack);
int isEmpty(Stack *stack);

#endif STACK_H

stack.c

#include <stdio.h>
#include <stdlib.h>

#include "stack.h"

Stack *createStack(int capacity) {
    if (capacity < 1) {
        puts("Stack capacity must be greater than 0.");
        exit(1);
    }

    Stack *stack = (Stack *) malloc(sizeof(Stack));
    if (stack == NULL) {
        puts("Error allocating memory for stack.");
        exit(1);
    }

    stackElement *arr = (stackElement *) malloc(capacity * sizeof(stackElement));
    if (arr == NULL) {
        puts("Error allocating memory for internal array.");
        exit(1);
    }

    stack->capacity = capacity;
    stack->top = -1;
    stack->arr = arr;

    return stack;
}

void push(Stack *stack, stackElement el) {
    if (isFull(stack)) {
        puts("Push to full stack.");
        exit(1);
    }

    stack->top++;
    *(stack->arr + stack->top) = el;
}

stackElement pop(Stack *stack) {
    if (isEmpty(stack)) {
        puts("Pop from empty stack.");
        exit(1);
    }

    stackElement val = *(stack->arr + stack->top);
    stack->top--;

    return val;
}

stackElement peek(Stack *stack) {
    if (isEmpty(stack)) {
        puts("Peek from empty stack.");
        exit(1);
    }

    return *(stack->arr + stack->top);
}

int capacity(Stack *stack) {
    return stack->capacity;
}

int size(Stack *stack) {
    return stack->top + 1;
}

int isFull(Stack *stack) {
    return stack->top >= stack->capacity - 1;
}

int isEmpty(Stack *stack) {
    return stack->top < 0;
}

void destroyStack(Stack *stack) {
    if (stack == NULL)
        return;

    free(stack->arr);
    stack->top = -1;
    free(stack);
}

main.c

#include <stdio.h>
#include "stack.h"


// Forward declaration
void printSizeAndCapacity(Stack *stack);


int main() {
    Stack *stack = createStack(5);

    printSizeAndCapacity(stack);

    int i = 0;
    while (!isFull(stack)) {
        push(stack, ++i);
    }

    printSizeAndCapacity(stack);

    while (!isEmpty(stack)) {
        printf("\nPeek: %7d\n", peek(stack));
        printf("Pop: %8d\n", pop(stack));
    }

    printSizeAndCapacity(stack);

    destroyStack(stack);

    return 0;
}


void printSizeAndCapacity(Stack *stack) {
    printf("\nCapacity: %3d\n", capacity(stack));
    printf("Size: %7d\n\n", size(stack));
}

Contents