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
- tuts/c/tutorials/hash_table_from_scratch Linked here; links to this page; shared tags: #c, #dsa, #prog, #tutorials
- tuts/c/tutorials Linked here; links to this page; shared tags: #c, #prog, #tutorials
- tuts/c/pointers_and_memory/dynamic_memory_and_allocators Linked here; shared tags: #c, #prog
- tuts/programming/algorithms_and_dsa/linear_and_hashed_structures Linked here; shared tags: #dsa, #prog
- tuts/c/tutorials/arena_allocator_pattern shared tags: #c, #prog, #tutorials
- tuts/c/tutorials/c_shared_library_with_python_ctypes shared tags: #c, #prog, #tutorials
- tuts/c shared tags: #c, #prog
- tuts/c/builtins shared tags: #c, #prog
- tuts/c/builtins/__FILE__ shared tags: #c, #prog
- tuts/c/builtins/__func__ shared tags: #c, #prog