Most of the time, you won’t need to access the underlying data buffer of a vector. However, there are exceptional circumstances under which accessing the raw memory buffer is needed. Here's how you can do it portably.
Suppose you have a vector of int and function that takes int *. To obtain the address of the internal array of the vector vec use the expressions &v or &*v.front(). For example:
void f(const int arr, std::size_t len);
vector <int> vec;
//.. fill vec
The C++03 Standard guarantees that vector elements shall occupy contiguous memory so the address of the first element is also the address of the entire array. Notice that some implementations also offer a vector::data() member function which returns the address of the internal vector buffer. However, data() isn't portable.
Take advantage of special member promotions, everyday discounts, quick access to saved content, and more! Join Today.