Skip to content

Instantly share code, notes, and snippets.

@DenisBelmondo
Created January 31, 2024 08:20
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save DenisBelmondo/464901d4568fcfe6847bf0a9d05f3577 to your computer and use it in GitHub Desktop.
Save DenisBelmondo/464901d4568fcfe6847bf0a9d05f3577 to your computer and use it in GitHub Desktop.
c89 type safe dynamic array
#ifndef ARRAY_H
#define ARRAY_H
#include <stddef.h>
#include <stdlib.h>
#include <string.h>
#define Array(T)\
struct {\
T *data;\
size_t count;\
size_t capacity;\
}
#define array_init(ARRAY) do {\
memset((ARRAY), 0, sizeof(*(ARRAY)));\
(ARRAY)->data = malloc(sizeof(*(ARRAY)));\
(ARRAY)->capacity = 1;\
} while (0)\
#define array_push_back(ARRAY, VALUE) do {\
void *data = (ARRAY)->data;\
size_t new_count = (ARRAY)->count + 1;\
size_t new_capacity = (ARRAY)->capacity;\
\
if (new_count > (ARRAY)->capacity) {\
new_capacity *= 2;\
data = realloc(data, new_capacity * sizeof(*((ARRAY)->data)));\
\
if (data) {\
(ARRAY)->data = data; \
}\
}\
\
(ARRAY)->data[(ARRAY)->count++] = VALUE;\
(ARRAY)->capacity = new_capacity;\
} while (0)
#define array_push_front(ARRAY, VALUE) do {\
void *old_buf, *new_buf;\
size_t new_count = (ARRAY)->count + 1;\
size_t new_capacity = (ARRAY)->capacity;\
\
old_buf = (ARRAY)->data; \
\
if (new_count > (ARRAY)->capacity) {\
new_capacity *= 2;\
new_buf = malloc(new_capacity * sizeof(*((ARRAY)->data)));\
memcpy((char *)new_buf + sizeof(*((ARRAY)->data)), (ARRAY)->data, sizeof(*((ARRAY)->data)) * new_count);\
\
if (new_buf) {\
(ARRAY)->data = new_buf; \
free(old_buf);\
}\
}\
\
(ARRAY)->data[0] = VALUE;\
(ARRAY)->count = new_count;\
(ARRAY)->capacity = new_capacity;\
} while (0)
#define array_pop_back(ARRAY)\
(ARRAY)->data[--(ARRAY)->count]\
#define array_pop_front(ARRAY)\
(ARRAY)->data[(ARRAY)->count - (ARRAY)->count--];
#define array_deinit(ARRAY) do {\
free((ARRAY)->data);\
} while (0)
#endif /* ARRAY_H */
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment