C Collections

cvector · Section 3

cvec_init

cvec_init - create the vector behind a declared handle (fatal on failure)

C Collections (libccollections, -lccollections)

#include <ccollections/cvector.h>
 
cvec_init(v);

Creates a vector through the default allocator and stores it in v, which
cvec_declare(3) or cvec_declare_scoped(3) has to declare first. The
element size comes from the element type of that declaration, so nothing
about the type is repeated here. cvec_init_mp(3) is the form that takes
an allocator of its own.
 
cvec_construct(3) folds this step into the declaration. Keep the declare
step and the initialize step apart when they can't sit on one line, for
example when the choice between the default allocator and a custom one is
made further down the function.
 
The new vector is empty and starts at the minimum capacity of 4. The
capacity doubles when a push finds the buffer full and halves when the
element count drops below a quarter of it, but it never goes below that
minimum of 4.

v  Name of the vector variable that receives the new vector; it must be a
   plain identifier. cvec_declare(3) or cvec_declare_scoped(3) must have
   declared it, and its companion type variables must be in scope.

None. The macro expands to a statement, not to an expression.

When it cannot create the vector, the macro stops the program through
ccol__fatal_err() with a message that names v and the underlying
error.  To handle a failed creation yourself, call cvector_create(3)
directly, which does not stop the program.
The element size comes from the declared element type, so the macro
does not compile for a handle whose companion type variables are out
of scope.
The macro expands to a do/while block, so the call site needs a
semicolon at the end.
The macro evaluates v more than once and pastes v into the names of
the companion variables, so v must be a plain identifier and never an
expression.
Free a vector from this macro with cvec_destroy(3);
cvec_declare_scoped(3) makes that call for you at the end of the
scope.

cvec_declare(my_vec, int);
cvec_init(my_vec);
cvec_push(my_vec, 42);
cvec_destroy(my_vec);

cvec_init_mp(3), cvec_declare(3), cvec_declare_scoped(3), cvec_construct(3), cvec_destroy(3), cvector_create(3)