How can I access the contiguous memory buffer used within a std::vector so I can perform direct memory operations on it (e.g. memcpy)? Also, it is safe to perform operations like memcpy on that buffer?
I've read that the standard guarantees that a vector uses a contiguous memory buffer internally, but that it is not necessarily implemented as a dynamic array. I figure given that it is definitely contiguous, I should be able to use it as such - but I wasn't sure if the vector implementation stored book-keeping data as part of that buffer. If it did, then something like memcpying the vector buffer would destroy its internal state.
In practice, virtually all compilers implement vector
as an array under the hood. You can get a pointer to this array by doing &somevector[0]
. If the contents of the vector are POD ('plain-old-data') types, doing memcpy
should be safe - however if they're C++ classes with complex initialization logic, you'd be safer using std::copy.
Simply do
&vec[0];
// or Goz's suggestion:
&vec.front();
// or
&*vec.begin();
// but I don't know why you'd want to do that
This returns the address of the first element in the vector (assuming vec
has more than 0
elements), which is the address of the array it uses. vector
storage is guaranteed by the standard to be contiguous, so this is a safe way to use a vector with functions that expect arrays.
Be aware that if you add, or remove elements from the vector, or [potentially] modify the vector in any way (such as calling reserve
), this pointer could become invalid and point to a deallocated area of memory.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With