Sheldon Simms said:
Yes, but that's not a problem. Don't realloc for every element. Each time
you run out of elements, use realloc to double the size of the array.
That's actually very good strategy with which I made good experiences.
If he uses a structure type, he can write a set of functions to handle the
case universally, like
#include <stddef.h>
#include <string.h>
#include <stdlib.h>
#include <limits.h>
typedef struct { void* buf; size_t elsz; size_t size; size_t used; }
dynamic_array_t;
typedef dynamic_array_t* dynamic_array_pointer_t;
dynamic_array_pointer_t create_dynamic_array( size_t elsz, size_t
initial ) {
dynamic_array_pointer_t da = (dynamic_array_pointer_t) malloc(
sizeof(dynamic_array_t) );
if ( da == 0 ) return 0;
da->buf = malloc( elsz * initial ); da->elsz = elsz; da->size =
initial; da->used = 0; return da;
}
void delete_dynamic_array( dynamic_array_pointer da ) { free( da.buf );
free( da ); }
void* address_dynamic_array_element_readonly( dynamic_array_pointer da,
size_t index ) {
if ( index >= da->used ) return 0;
{ char* p = (char*) da->buf; return p+( da->elsz * index ); }
}
void* address_dynamic_array_element_readwrite( dynamic_array_pointer da,
size_t index ) {
if ( index >= da->used ) {
if ( index >= da->size ) {
size_t newsz; void* newbf;
if ( index >= UINT_MAX / da->elsz ) return 0;
if ( da->size >= UINT_MAX / 2U ) newsz = UINT_MAX /
da->elsz; else newsz = da->size * 2U;
if ( index >= newsz ) newsz = index + 1U;
newbf = malloc( da->elsz * newsz ); if ( newbf == 0 ) return
0;
if ( da->used ) memcpy( newbf, da->buf, da->used *
da->elsz );
free( da->buf ); da->buf = newbf; da->size = newsz;
}
da->used = index + 1U;
}
{ char* p = (char*) da->buf; return p+( da->elsz * index ); }
}
Here, the functions create_dynamic_array() and delete_dynamic_array() handle
array creation / destruction, and address_dynamic_array_element_readonly()
and address_dynamic_array_element_readwrite() access the array for reading
and writing and return a pointer to an indexed array element. If during
write indexing, the index goes beyond the array size, it is automatically
resized to either twice the size, or a size including the indexed element.
This way, you can have arbitrary access to the array and can use it for many
kinds of purposes.