Header-only generic dynamic array library for C.
This library provides dynamic arrays using malloc, realloc, and macros while keeping a clean array-like interface.
Internally, metadata is stored directly before the array in memory, allowing automatic resizing and efficient access to size and capacity information.
The library works with any data type.
- Generic dynamic arrays for any data type
- Header-only implementation
- Automatic resizing using
realloc - Automatic shrinking when usage drops below 25%
- Metadata stored internally
- Simple macro-based API
- Pre-allocation support
- Contiguous memory layout
Simply include the header file in your project:
#include "dynamic_arrays.h"Compile normally:
gcc main.c -o app#include "dynamic_arrays.h"
int main(void) {
int *arr = vector_create(int);
vector_push_back(arr, 10);
vector_push_back(arr, 20);
vector_push_back(arr, 30);
vector_print(arr, "%d");
vector_delete_element(arr, 1);
vector_print(arr, "%d");
vector_reuse(arr);
vector_print(arr, "%d");
vector_free(arr);
return 0;
}Creates a dynamic array.
int *arr = vector_create(int);int *arr = vector_create(int, 100);Appends an element to the vector.
vector_push_back(arr, value);Deletes an element by index and shifts remaining elements left.
vector_delete_element(arr, index);Prints the vector using the supplied format specifier.
vector_print(arr, "%d");Resets the vector size to 0 without freeing allocated memory.
vector_reuse(arr);Frees all memory associated with the vector.
vector_free(arr);Returns the current number of elements stored in the vector.
vector_size(arr);Returns the current allocated capacity of the vector.
vector_capacity(arr);| Operation | Complexity |
|---|---|
vector_push_back() |
Amortized O(1) |
vector_delete_element() |
O(n) |
vector_size() |
O(1) |
vector_capacity() |
O(1) |
The vector internally stores metadata before the actual array memory.
+-----------+----------------------+
| metadata | actual array memory |
+-----------+----------------------+
^
returned pointer
The metadata stores:
- Current size
- Current capacity
- Element size
This allows the library to expose a clean array-like interface while still supporting dynamic resizing internally.
- The vector pointer may change after
vector_push_back()because ofrealloc - Always use the same vector variable after operations
- Memory must be released using
vector_free() - The library is not thread-safe
MIT License