What is a->data
initialized to? For this to work, it should be set to NULL when the (empty) array is created.
Also, you address computation does not take pointers arithmetics into account. a->data
is a pointer (to void *), so the (a->size - 1)*a->element_size
offset will be multiplied by the size of a pointer (to void *).
Setting a->data
to void *
should cause a compiler error since void
has no size.
If you really want to do this, better declare a->data
as a char *
, which is guaranteed to have a size of 1.
Beware: accessing your array will require a cast to (element*
). This will prevent you from using square brackets.
You will have to provide an accessor function like
void * array_at(size_t index) { return &a->data[index*a->element_size]; }
and then the caller will have to cast the resutl into element *
.
Creating a dynamic array of element
s directly seems more practical to me.
You can still call realloc
on it if you want.
But the first question that springs to my mind is: why do you want your data to be stored in a contiguous block?
This is not as memory-efficient as you might think, since calling realloc()
repeatedly will stress the memory allocator, waste time doing copies and possibly fragment the heap even more than a collection of individual malloc
s.