typestar

dynamic_stack.c in C

A growable integer stack backed by malloc and realloc.

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

typedef struct {
    int *items;
    size_t len;
    size_t cap;
} Stack;

static void push(Stack *s, int value) {
    if (s->len == s->cap) {
        s->cap = s->cap ? s->cap * 2 : 4;
        s->items = realloc(s->items, s->cap * sizeof(int));
    }
    s->items[s->len++] = value;
}

static int pop(Stack *s) {
    return s->len ? s->items[--s->len] : 0;
}

int main(void) {
    Stack s = {0};
    for (int i = 1; i <= 10; i++)
        push(&s, i * i);
    long total = 0;
    while (s.len)
        total += pop(&s);
    printf("sum of squares: %ld\n", total);
    free(s.items);
    return 0;
}

How it works

  1. push doubles capacity with realloc when full.
  2. pop returns and removes the top item.
  3. main fills, drains, and frees the stack.

Keywords and builtins used here

The run, in numbers

Lines
32
Characters to type
549
Tokens
218
Three-star pace
105 tpm

At the three-star pace of 105 tokens a minute, this run takes about 125 seconds.

Type this snippet

Step 1 of 2 in Encore, step 24 of 25 in Pointers & memory.

← Previous Next →