Is it safe to pass a vector as an array? Is it safe to pass a vector as an array? arrays arrays

Is it safe to pass a vector as an array?


From section 23.2.4, point 1 of the standard:

[...] The elements of a vector are stored contiguously, meaning that if v is a vector where T is some type other than bool, then it obeys the identity &v[n] == &v[0] + n for all 0 <= n < v.size().

So yes, it is safe.

Note: If v is empty v[0] is undefined behavior so you should only do this if v is not empty.


As others has suggested it is safe.

But I would like to have a small reservation.If this function accept an array and stores it for later use you might have a problem. This is because std::vector might freely deallocate its memory if it needs it to change size. So if this function just uses the array (makes a copy or whatever) or you never alter it, it is safe.

I just want to point that out, just because the vectors elements are stored contiguous it isn't automatically safe to pass around. Ownership is still an issue.


Yes. Assuming v.size() > 0, this is safe (If the vector is empty, then v[0] results in undefined behavior).

The elements of a std::vector container are stored contiguously, just like in an ordinary array.