4 ms·
Allocating memory on initialisation is a bit questionable. It's better to alloc no memory and let the growth logic handle that case (either by checking for zero
by gsg 14y ago
Allocating memory on initialisation is a bit questionable. It's better to alloc no memory and let the growth logic handle that case (either by checking for zero or by including an offset, such as vec->capacity += vec->capacity + 2).
The reason is code like this:
vector vec;
vector_init(&vec);
for (i = 0; i < n; i++)
vector_append(vec, some_operation(n));
whole_vector_operation(&vec);
vector_free(&vec);
It's both natural and desirable for this code to do no allocation when n = 0.
Since this is C, you might also include a macro to allow for static initialisation: #define VECTOR_INIT { 0, NULL, NULL } or something.