Using std::vector as a C array

suggest change

There are several ways to use a std::vector as a C array (for example, for compatibility with C libraries). This is possible because the elements in a vector are stored contiguously. std::vector<bool> is the exception: it does not store the elements as a contiguous array of bool, and it has no data() member.

std::vector<int> v{ 1, 2, 3 };
int* p = v.data();

In contrast to solutions based on previous C++ standards (see below), the member function .data() may also be applied to empty vectors, because it doesn’t cause undefined behavior in this case.

Before C++11, take the address of the first element. When the vector is not empty, that pointer and .data() refer to the same place:

int* p = &v[0];      // combine subscript operator and 0 literal

int* p = &v.front(); // explicitly reference the first element

Note: If the vector is empty, v[0] and v.front() are undefined and cannot be used.

When storing the base address of the vector’s data, note that many operations (such as push_back, resize, etc.) can change the data memory location of the vector, thus invalidating previous data pointers. For example:

std::vector<int> v;
int* p = v.data();
v.resize(42);      // may reallocate; do not use an old pointer to the vector's elements

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents