Skip to content

Instantly share code, notes, and snippets.

@lotherk
Last active January 11, 2017 12:51
Show Gist options
  • Save lotherk/78914d00bd260398ca69bde7834400fa to your computer and use it in GitHub Desktop.
Save lotherk/78914d00bd260398ca69bde7834400fa to your computer and use it in GitHub Desktop.
#include <stdio.h>
#include <stdlib.h>
typedef struct array {
void *array;
size_t used;
size_t size;
} array_t;
// initializes an array.
// param type data type (int, char, void*, etc...)
// param arr array_t*
// param s initialize array size
#define A_INIT(type, arr, s) arr = malloc(sizeof(array_t)); \
arr->array = (type *) malloc(s * sizeof(type)); \
arr->used = 0; \
arr->size = s;
// add element to array
// param type data type (int, char, ...)
// param arr array_t* to add the element to
// param e element to add
#define A_ADD(type, arr, e) if(arr->used == arr->size) { \
arr->size += 64; \
printf("Resizing... to %i\n", arr->size); \
arr->array = (type *)realloc(arr->array, arr->size * sizeof(type)); \
} \
((type *)arr->array)[arr->used++] = e;
// get element from array
// param type data type (int, char, ...)
// param arr array_t* to get the element from
// param index index to return
#define A_GET(type, arr, index) ((type *)arr->array)[index]
// iterate array_t*
// param type data type (int, char, ...)
// param arr array_t* to get the element from
// param e element to use inside the iteration
// param i counter
#define A_EACH(type, arr, e, i) for(i = 0; i < arr->used; i++) { \
type e = A_GET(type, arr, i);
#define A_END }
int main() {
array_t *a;
A_INIT(int, a, 10);
for(int i = 0; i < 2048; i++) {
A_ADD(int, a, i * 2);
}
for(int i = 0; i < a->used; i++) {
printf("%i\n", A_GET(int, a, i));
}
// array_t of array_t's
array_t *b;
A_INIT(array_t*, b, 0);
A_ADD(array_t*, b, a);
array_t *c = A_GET(array_t*, b, 0);
printf("%i!\n", A_GET(int, c, 5));
// each element
int counter;
A_EACH(int, c, elem, counter) {
printf("Elem %i: %i\n", counter, elem);
} A_END
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment