Skip to content

Instantly share code, notes, and snippets.

Created June 30, 2011 09:25
Show Gist options
  • Save anonymous/1055918 to your computer and use it in GitHub Desktop.
Save anonymous/1055918 to your computer and use it in GitHub Desktop.
Array C "template"
#include <stdio.h>
#define ARRAY_DECLARE(type) \
typedef struct \
{ \
type *buffer; \
size_t capacity; \
size_t size; \
} type##_array; \
void type##_array_create(type##_array* container); \
void type##_array_destroy(type##_array* container); \
int type##_array_grow(type##_array *container, size_t size); \
int type##_array_push(type##_array *container, type* element); \
#define ARRAY(type) type##_array
#define ARRAY_FUNC(type, func) type##_array_##func
#define ARRAY_DEFINE(type) \
void type##_array_create(type##_array* container) \
{ \
container->buffer = NULL; \
container->capacity = 1; \
container->size = 0; \
} \
void type##_array_destroy(type##_array* container) \
{ \
if(container->buffer != NULL) \
{ \
free(container->buffer); \
container->buffer = NULL; \
} \
container->capacity = container->size = 0; \
} \
int type##_array_grow(type##_array *container, size_t size) \
{ \
size_t capacity = container->capacity + size; \
type* tmp; \
tmp = (type*)realloc(container->buffer, capacity*sizeof(type)); \
if(tmp == NULL) \
{ \
return 0; \
} \
container->capacity = capacity; \
container->buffer = tmp; \
return 1; \
} \
int type##_array_push(type##_array *container, type* element) \
{ \
container->size++; \
if(container->size >= container->capacity) \
{ \
if(! type ## _array_grow(container, container->capacity) ) \
{ \
return 0; \
} \
} \
memcpy(container->buffer+container->size-1, element, sizeof(type)); \
return 1; \
}
ARRAY_DECLARE(int);
ARRAY_DEFINE(int);
int main()
{
int a, i;
ARRAY(int) bozo;
ARRAY_FUNC(int, create)( &bozo );
for(i=0; i<17; i++)
{
a = i ^ 0xff;
ARRAY_FUNC(int, push)( &bozo, &a );
}
for(i=0; i<bozo.size; i++)
{
printf("%d\n", bozo.buffer[i]);
}
ARRAY_FUNC(int, destroy)( &bozo );
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment