C++ std::vector Using std::vector as a C array

Help us to keep this website almost Ad Free! It takes only 10 seconds of your time:
> Step 1: Go view our video on YouTube: EF Core Bulk Extensions
> Step 2: And Like the video. BONUS: You can also share it!

Example

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.

C++11
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, you would take the address of the vector's first element to get an equivalent pointer, if the vector isn't empty, these both methods are interchangeable:

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);      // internal memory location changed; value of p is now invalid


Got any C++ Question?