Skip to content

Instantly share code, notes, and snippets.

@bynect
Last active March 16, 2021 21:28
Show Gist options
  • Save bynect/5f3c120392b2658b36847aa60e6b7904 to your computer and use it in GitHub Desktop.
Save bynect/5f3c120392b2658b36847aa60e6b7904 to your computer and use it in GitHub Desktop.
Generic vector implementation in C using preprocessor macros.
#ifndef VECTOR_H
#define VECTOR_H
#include <stdint.h>
#include <stddef.h>
#include <malloc.h>
#define VECTOR(_type) VECTOR_##_type##_t
#define VECTOR_INIT(_type, _vec) VECTOR_##_type##init(_vec)
#define VECTOR_FREE(_type, _vec) VECTOR_##_type##free(_vec)
#define VECTOR_PUSH(_type, _vec, _item) VECTOR_##_type##push(_vec, _item)
#define VECTOR_POP(_type, _vec) VECTOR_##_type##pop(_vec)
#define VECTOR_STUB(_type) \
typedef struct { \
_type *items; \
size_t count; \
size_t size; \
} VECTOR(_type); \
\
void \
VECTOR_##_type##init(VECTOR(_type) * vec) { \
vec->items = NULL; \
vec->count = 0; \
vec->size = 0; \
} \
\
void \
VECTOR_##_type##free(VECTOR(_type) * vec) { \
free(vec->items); \
vec->count = 0; \
vec->size = 0; \
} \
\
void \
VECTOR_##_type##push(VECTOR(_type) * vec, _type item) { \
if (vec->size < vec->count + 1) { \
vec->size = (vec->size < 8 ? 8 : vec->size * 2); \
vec->items = realloc( \
vec->items, vec->size * sizeof(_type) \
); \
} \
vec->items[vec->count++] = item; \
} \
\
_type \
VECTOR_##_type##pop(VECTOR(_type) * vec) { \
/*XXX CHECK COUNT TO PREVENT BUFFER UNDERFLOW*/ \
return vec->items[vec->count--]; \
}
#endif /* VECTOR_H */
#include <vector.h>
// DECLARE VECTOR
VECTOR_STUB(int)
int main() {
VECTOR(int) vec;
VECTOR_INIT(int, &vec);
for (int i = 200; i > 0; i--)
VECTOR_PUSH(int, &vec, i);
for (int i = 0; i < 100; i++) {
int x = VECTOR_POP(int, &vec);
printf("%d ==> %d\n", i, x);
}
VECTOR_FREE(int, &vec);
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment