I created a simple dynamic array in C.
typedef struct varray_t
{
void **memory;
size_t allocated;
size_t used;
int index;
} varray;
void
varray_init(varray **array)
{
*array = (varray*) malloc (sizeof(varray));
(*array)->memory = NULL;
(*array)->allocated = 0;
(*array)->used = 0;
(*array)->index = -1;
}
void
varray_push(varray *array, void *data, size_t size)
{
if ((array->allocated - array->used) < size) {
array->memory = realloc(array->memory, array->allocated + size);
array->allocated = array->allocated + size;
}
array->used = array->used + size;
array->memory[++array->index] = data;
}
int
varray_length(varray *array)
{
return array->index + 1;
}
void
varray_clear(varray *array)
{
int i;
for(i = 0; i < varray_length(array); i++)
{
array->memory[i] = NULL;
}
array->used = 0;
array->index = -1;
}
void
varray_free(varray *array)
{
free(array->memory);
free(array);
}
void*
varray_get(varray *array, int index)
{
if (index < 0 || index > array->index)
return NULL;
return array->memory[index];
}
It works great. But in order to add an element to the array, the caller must pass the size of the added element. I can not find another way to get the size from the passed in void*. I am wondering if there is a better way for the design varray_push(varray *array, void *data, size_t size)to sizebe able to deduce?
Any help would be great
Edited code after sentences
My array will contain only pointer elements. I changed the code as suggested by Blastfurnace. The new code will use sizeof(void*)and resize the memory using a constant proposition to get the amortized constant time on the inserts.
void
varray_push(varray *array, void *data)
{
size_t toallocate;
size_t size = sizeof(void*);
if ((array->allocated - array->used) < size) {
toallocate = array->allocated == 0 ? size : (array->allocated * 2);
array->memory = realloc(array->memory, toallocate);
array->allocated = array->allocated + toallocate;
}
array->memory[++array->index] = data;
array->used = array->used + size;
}