Created
December 28, 2021 03:56
-
-
Save RealNeGate/ffbf934951ea2890707db0a0fe6354cd to your computer and use it in GitHub Desktop.
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 <stdlib.h> | |
| #include <stdint.h> | |
| #include <stdio.h> | |
| #define INITIAL_CAP 64 | |
| typedef struct ArrayHeader { | |
| // honestly storing the type size is kinda weird | |
| size_t size, capacity; | |
| char data[]; | |
| } ArrayHeader; | |
| void* __array_create(size_t type_size) { | |
| ArrayHeader* header = malloc(sizeof(ArrayHeader) + (type_size * INITIAL_CAP)); | |
| *header = (ArrayHeader){ | |
| .size = 0, | |
| .capacity = INITIAL_CAP | |
| }; | |
| return &header->data[0]; | |
| } | |
| void __array_destroy(void* ptr) { | |
| ArrayHeader* header = ((ArrayHeader*) ptr) - 1; | |
| free(header); | |
| } | |
| void* __array_reserve(void* ptr, size_t type_size, size_t extra) { | |
| ArrayHeader* header = ((ArrayHeader*) ptr) - 1; | |
| // I mean you can make a better expansion pattern if you care idk tho | |
| if (header->size + extra >= header->capacity) { | |
| header->capacity = (header->size + extra) * 2; | |
| ArrayHeader* new_ptr = realloc(header, sizeof(ArrayHeader) + (type_size * header->capacity)); | |
| if (!new_ptr) abort(); | |
| return &new_ptr->data[0]; | |
| } | |
| return ptr; | |
| } | |
| #define array_create(T) __array_create(sizeof(T)) | |
| #define array_destroy(arr) __array_destroy(&arr) | |
| #define array_put(arr, new_data) do { \ | |
| arr = __array_reserve(arr, sizeof(*arr), 1); \ | |
| ArrayHeader* header = ((ArrayHeader*) arr) - 1; \ | |
| arr[header->size++] = (new_data); \ | |
| } while (0) | |
| #define array_length(arr) ((((ArrayHeader*) (arr)) - 1)->size) | |
| int main() { | |
| int* arr = array_create(int); | |
| printf("%p\n\n", arr); | |
| for (size_t i = 0; i < 100; i++) { | |
| array_put(arr, 16); | |
| array_put(arr, 24); | |
| } | |
| size_t l = array_length(arr); | |
| for (size_t i = 0; i < l; i++) { | |
| printf("%d\n", arr[i]); | |
| } | |
| return 0; | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment