On this page
  1. Dynamic Array Implementation
  2. Contents
  3. Growable IntVec with Geometric Resizing

Dynamic Array Implementation

Prev: tutorials | Up: tutorials | Next: Hash Table from Scratch
Rel: Dynamic Memory & Allocators, Linear & Hashed Structures
Ref: cppreference — realloc
Tags: #public #prog #c #tutorials #dsa


Contents


Growable IntVec with Geometric Resizing

Doubling capacity on overflow yields amortized $O(1)$ append while keeping elements contiguous in memory for CPU cache locality:

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

typedef struct {
    int   *data;
    size_t len;
    size_t cap;
} IntVec;

static bool intvec_push(IntVec *v, int value) {
    if (v->len == v->cap) {
        size_t next_cap = v->cap ? v->cap * 2 : 8;
        int *tmp = realloc(v->data, next_cap * sizeof(*tmp));
        if (!tmp) return false;
        v->data = tmp;
        v->cap = next_cap;
    }
    v->data[v->len++] = value;
    return true;
}

static void intvec_free(IntVec *v) {
    free(v->data);
    v->data = NULL;
    v->len = v->cap = 0;
}

int main(void) {
    IntVec v = {0};
    for (int i = 0; i < 12; i++) {
        if (!intvec_push(&v, i * 10)) {
            intvec_free(&v);
            return 1;
        }
    }
    printf("len=%zu cap=%zu last=%d\n", v.len, v.cap, v.data[v.len - 1]);
    intvec_free(&v);
    return 0;
}

Linked from

Related notes