Dynamically growing an array using realloc() is error prone and boring.
Define your array with:
-
a pointer (
item
) that points at the array, initialized toNULL
(although please name the variable based on its contents, not on its type); -
an integer variable (
alloc
) that keeps track of how big the current allocation is, initialized to0
; -
another integer variable (
nr
) to keep track of how many elements the array currently has, initialized to0
.
Then before adding n`th element to the item, call `ALLOC_GROW(item, n,
alloc)
. This ensures that the array can hold at least n
elements by
calling realloc(3)
and adjusting alloc
variable.
sometype *item;
size_t nr;
size_t alloc
for (i = 0; i < nr; i++)
if (we like item[i] already)
return;
/* we did not like any existing one, so add one */
ALLOC_GROW(item, nr + 1, alloc);
item[nr++] = value you like;
You are responsible for updating the nr
variable.
If you need to specify the number of elements to allocate explicitly
then use the macro REALLOC_ARRAY(item, alloc)
instead of ALLOC_GROW
.