Home > Blogs > 30 C++ Tips in 30 Days: Tip # 7 Accessing a vector's Internal buffer portably

30 C++ Tips in 30 Days: Tip # 7 Accessing a vector's Internal buffer portably

By  Nov 25, 2007

Topics: Programming, C/C++

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[0] or &*v.front(). For example:

void f(const int arr[], std::size_t len);
int main()
{
 vector <int> vec;
 //.. fill vec
 f(&vi[0], vi.size());
}

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.