https://github.com/eignnx/dynarray
A generic dynamic array implementation in C.
https://github.com/eignnx/dynarray
c generics vector
Last synced: 8 months ago
JSON representation
A generic dynamic array implementation in C.
- Host: GitHub
- URL: https://github.com/eignnx/dynarray
- Owner: eignnx
- License: mit
- Created: 2018-01-31T22:55:40.000Z (over 8 years ago)
- Default Branch: master
- Last Pushed: 2025-05-06T15:45:14.000Z (about 1 year ago)
- Last Synced: 2025-07-10T19:55:24.899Z (12 months ago)
- Topics: c, generics, vector
- Language: C
- Size: 58.6 KB
- Stars: 27
- Watchers: 0
- Forks: 1
- Open Issues: 5
-
Metadata Files:
- Readme: README.md
- License: LICENSE
Awesome Lists containing this project
README
# dynarray
A generic dynamic array implementation in C. A dynarray of type `T` can be passed to any function that operates on vanilla `T` arrays. Inspiration taken from [this article](https://solarianprogrammer.com/2017/01/08/c99-c11-dynamic-array-mimics-cpp-vector-api-improvements/) by [solarianprogrammer](https://solarianprogrammer.com/).
## Example Usage
```c
#include "dynarray.h"
int *v = dynarray_create(int);
for (int i = 0; i < 10; i++) {
dynarray_push(v, i);
dynarray_push_rval(v, 100 - i);
}
for (int i = 0; i < dynarray_length(v); i++) {
printf("v[%d] -> %d\n", i, v[i]);
}
dynarray_destroy(v);
```
Output:
```
v[0] -> 0
v[1] -> 100
v[2] -> 1
v[3] -> 99
...
v[18] -> 9
v[19] -> 91
```
## Memory Layout
The array is heap-allocated and is prefixed with a three-field header containing the buffer's `capacity`, `length`, and `stride`.
* The `stride` is calculated at creation time as `sizeof(T)` where `T` is the datatype you intend to store.
* The `capacity` field stores the buffer's size.
* The `length` field keeps track of the number of elements stored in the buffer.
Macros defined in [`dynarray.h`](dynarray.h) allow the `capacity`, `length`, and `stride` attributes to be accessed.
A dynarray is referred to _only_ by a pointer to the first element in its buffer. **This allows a dynarray to be passed to any function that operates on regular C-arrays.**
