cvector · Section 3
cvec_data_ptr
NAME
cvec_data_ptr - get a pointer to a vector's contiguous backing store
LIBRARY
C Collections (libccollections, -lccollections)
SYNOPSIS
#include <ccollections/cvector.h> void *p = cvec_data_ptr(v);
DESCRIPTION
A wrapper for cvector_data_ptr() that gives a pointer to the start of the vector's contiguous backing store, so you can hand the elements to any C interface that expects a plain array. The pointer leads to the vector's own storage, not a copy, and writing through it changes the content of the vector. The result is a void *; assign it to a pointer of the vector's element type at the call site.
PARAMETERS
v Vector to get the data pointer from
RETURN VALUE
A pointer to the first element of the backing store.
NOTES
The buffer covers the whole capacity of the vector, but only the first cvec_size(3) elements hold values. Don't free this pointer; the vector owns it and frees it when it is destroyed. The macro asserts when v is NULL.
WARNINGS
Any operation that can grow or shrink the backing store reallocates it and so invalidates the pointer. Those are cvec_push(3), cvec_append_array(3), cvec_append_cvec(3), cvec_reserve(3), cvec_reset(3), cvec_pop(3) and the destruction; cvec_pop(3) shrinks the store when the vector drops below a quarter full. Fetch the pointer again after any of them instead of keeping the old value. Passing this pointer straight back into cvec_append_array(3) or cvector_append_array(3) is safe, because those functions read their source through any reallocation that they start.
EXAMPLES
cvec_construct(vec, int); cvec_push(vec, 10); cvec_push(vec, 20); int *arr = cvec_data_ptr(vec); for (size_t i = 0; i < cvec_size(vec); i++) { printf("%d\n", arr[i]); } cvec_destroy(vec);