Created
March 26, 2026 19:27
-
-
Save sriramster/0e1d2cc6ee12b7f9f01d581f68be7d41 to your computer and use it in GitHub Desktop.
Dynamic generic array implementation.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| #include <stdio.h> | |
| #include <stdlib.h> | |
| typedef struct { | |
| size_t count; | |
| size_t capacity; | |
| } Header; | |
| #define ARR_INIT_CAPACITY 256 | |
| #define arr_push(arr, item) \ | |
| do { \ | |
| if (!arr) { \ | |
| Header * h = malloc(sizeof(item) * ARR_INIT_CAPACITY + sizeof(Header)); \ | |
| h->count = 1; \ | |
| h->capacity = ARR_INIT_CAPACITY; \ | |
| arr = (void *)(h + 1); \ | |
| } \ | |
| Header * h = (Header *)(arr) - 1; \ | |
| if (h->count > h->capacity) { \ | |
| h->capacity *= 2; \ | |
| realloc(h, sizeof(*arr) * h->capacity + sizeof(Header)); \ | |
| arr = (void *)(h + 1); \ | |
| } \ | |
| (arr)[sizeof(Header) * h->count] = item; \ | |
| } while (0); \ | |
| #define arr_len(arr) ((Header *)(arr) - 1)->count | |
| int main() { | |
| int * number = NULL; | |
| arr_push(number, 1); | |
| arr_push(number, 2); | |
| printf("%d\n", arr_len(number)); | |
| printf("%d\n", arr_capacity(number)); | |
| float * f = NULL; | |
| arr_push(f, 1.0); | |
| arr_push(f, 2.0); | |
| printf("%f\n", arr_len(f)); | |
| printf("%f\n", arr_capacity(f)); | |
| return 0; | |
| } | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment