Skip to content

Instantly share code, notes, and snippets.

@nzec
Last active July 30, 2023 11:54
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 nzec/7fdb71751b0dc22c91e9073e30b577a3 to your computer and use it in GitHub Desktop.
Save nzec/7fdb71751b0dc22c91e9073e30b577a3 to your computer and use it in GitHub Desktop.
vector in C
#include <stdio.h>
#include <stdlib.h>
#define VEC_NEW(type) struct vector { \
type *start; \
size_t cap; \
size_t size; \
} *
#define VEC_RESET(v) \
v = (typeof(v)) malloc(sizeof(typeof(v))); \
v->start = (typeof(v->start)) malloc(sizeof(typeof(*v->start))); \
v->cap = 0; \
v->size = 0
#define VEC_RESIZE(v, new_cap) \
v->start = (typeof(v->start)) realloc(v->start, new_cap); \
v->cap = new_cap; \
#define VEC_PUSH(v, val) \
if (v->cap == v->size) { VEC_RESIZE(v, (2 * v->cap + 1)) }\
v->start[v->size++] = val
#define VEC_POP(v) \
v->start[--v->size]
#define VEC_GET(v, idx) \
v->start[idx]
#define VEC_SIZE(v) \
v->size
#define VEC_CLEAR(v) \
v->size = 0;
int main() {
VEC_NEW(int) vec;
VEC_RESET(vec);
VEC_PUSH(vec, 10);
printf("%d\n", VEC_POP(vec));
VEC_PUSH(vec, 12);
VEC_PUSH(vec, 13);
VEC_PUSH(vec, 14);
VEC_PUSH(vec, 15);
VEC_PUSH(vec, 16);
printf("%d\n", VEC_POP(vec));
for (int i = 0; i < 4; i++) {
printf("%d\n", VEC_GET(vec, i));
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment