C Collections

cvector · Section 3

cvec_data_ptr

cvec_data_ptr - get a pointer to a vector's contiguous backing store

C Collections (libccollections, -lccollections)

#include <ccollections/cvector.h>
 
void *p = cvec_data_ptr(v);

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.

v    Vector to get the data pointer from

A pointer to the first element of the backing store.

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.

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.

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);

cvector_data_ptr(3), cvec_at_ptr(3), cvec_size(3)