Skip to content

Instantly share code, notes, and snippets.

@zshipko
Last active August 29, 2015 14:04
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 zshipko/bb7ceedb491b41d7c010 to your computer and use it in GitHub Desktop.
Save zshipko/bb7ceedb491b41d7c010 to your computer and use it in GitHub Desktop.
array.h
#ifndef __ARRAY_HEADER
#define __ARRAY_HEADER
// New Array: int *i = ARRAY(int, i);
#define ARRAY(t, n) calloc(0, sizeof(t)); size_t arr_##n##_count=0
// Add item: ARPUSH(i, 12);
#define ARRPUSH(a, n) a=realloc(a, sizeof(a[0])*(arr_##a##_count+1));\
a[arr_##a##_count]=n;\
arr_##a##_count+=1;
// Pop item: int i = ARRPOP(i);
#define ARRPOP(a) a[arr_##a##_count-1];\
a=realloc(a, sizeof(a[0])*(arr_##a##_count));\
arr_##a##_count-=1;
// Get number of elements: size_t count = ARRCOUNT(i);
#define ARRCOUNT(a) arr_##a##_count
// Get size of array(all elements) size_t sz = ARRSIZE(i);
#define ARRSIZE(a) arr_##a##_count*sizeof(a[0])
// Loop over each index: ARREACH(varname, arr){ printf("%d\n", arr[varname]); }
#define ARREACH(i, a) for(size_t i = 0; i < arr_##a##_count; i++)
#endif
// public domain (2014)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment