Last active
August 29, 2015 14:28
-
-
Save gyakoo/31d2a0886794ffabbd63 to your computer and use it in GitHub Desktop.
Small C snippet to have a dynamically allocated array (only few operations)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
struct flt_array; | |
typedef void (*flt_array_growpolicy)(flt_array*); | |
typedef struct flt_array | |
{ | |
void** data; | |
int size; | |
int capacity; | |
flt_array_growpolicy growpolicy; | |
}flt_array; | |
int flt_array_create(flt_array** arr, int capacity, flt_array_growpolicy grow) | |
{ | |
*arr = (flt_array*)flt_calloc(1,sizeof(flt_array)); | |
if ( !*arr ) return FLT_FALSE; | |
(*arr)->capacity = capacity>0?capacity:FLT_ARRAY_INITCAP; | |
(*arr)->size = 0; | |
(*arr)->data = (void**)flt_malloc(sizeof(void*)*capacity); | |
if ( !(*arr)->data ) { flt_array_destroy(arr); return FLT_FALSE; } | |
if ( !grow ) grow = flt_array_grow_double; | |
(*arr)->growpolicy = grow; | |
return FLT_TRUE; | |
} | |
void flt_array_destroy(flt_array** arr) | |
{ | |
if ( !arr || !*arr ) return; | |
flt_safefree((*arr)->data); | |
flt_free(*arr); | |
*arr=FLT_NULL; | |
} | |
void flt_array_grow_double(flt_array* arr) | |
{ | |
int newcap = arr->capacity*2; | |
arr->data = (void**)flt_realloc(arr->data, sizeof(void*)*newcap); | |
if( !arr->data ) { FLT_BREAK; return; } | |
arr->capacity = newcap; | |
} | |
void flt_array_push_back(flt_array* arr, void* elem) | |
{ | |
if (arr->size>=arr->capacity) | |
arr->growpolicy(arr); | |
arr->data[arr->size++]=elem; | |
} | |
void* flt_array_pop_back(flt_array* arr) | |
{ | |
if ( arr->size==0 ) return FLT_NULL; | |
return arr->data[--arr->size]; | |
} | |
void* flt_array_at(flt_array* arr, int index) | |
{ | |
return index >= 0 && index < arr->size ? arr->data[index] : FLT_NULL; | |
} | |
void flt_array_clear(flt_array* arr) | |
{ | |
arr->size=0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment