Skip to content

Instantly share code, notes, and snippets.

@nitish-pattanaik
Created March 6, 2025 04:59
Show Gist options
  • Save nitish-pattanaik/3a4c0feb393d97377c7180fb1b24b27c to your computer and use it in GitHub Desktop.
Save nitish-pattanaik/3a4c0feb393d97377c7180fb1b24b27c to your computer and use it in GitHub Desktop.
Dynamic array implementation in pure C23. Type agnostic and macro based.
#include <stdio.h>
#include <stdlib.h>
#define DA_INIT_CAP 256U // Initial Capacity
// Define the structure
#define DA_DEFINE(name, type) \
typedef struct { \
type *items; \
size_t count; \
size_t capacity; \
} name
// Initialize the structure members
#define da_init(xp) \
do { \
(xp)->items = nullptr; \
(xp)->count = 0; \
(xp)->capacity = 0; \
} while (0)
// Next Capacity: increase by 1.5 for smaller size & for bigger increases by 2
#define next_capacity(curr) ((curr) ? (((curr) < 1024) ? ((curr) * 3/2) : (curr) << 1): DA_INIT_CAP)
// da_append: append to the dynamic array
#define da_append(xp, x) \
do { \
if ((xp)->count >= (xp)->capacity) { \
(xp)->capacity = next_capacity((xp)->capacity); \
void *ptr = realloc((xp)->items, (xp)->capacity * (sizeof(*(xp)->items))); \
if (ptr == nullptr) { \
fprintf(stderr, "Memory allocation failed!\n"); \
exit(EXIT_FAILURE); \
} \
(xp)->items = ptr; \
} \
(xp)->items[(xp)->count++] = (x); \
} while (0)
// Free Dynamic Array
#define da_free(xp) \
do { \
free((xp)->items); \
(xp)->items = nullptr; \
(xp)->count = 0; \
(xp)->capacity = 0; \
} while (0)
DA_DEFINE(Integer, int);
int main(void)
{
Integer xs = {};
da_init(&xs);
for (int i = 0; i < 10; i++) {
da_append(&xs, i);
}
for (size_t i = 0; i < xs.count; i++) {
printf("%d\n", xs.items[i]);
}
da_free(&xs);
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment