Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can std::vector be treated like an array

Tags:

c++

stl

vector

Can a std::vector<char> be treated like an array in this way:

std::vector<char> v(10);
strncpy(&v[0], "hello", 9); // <-- Is this safe?
like image 680
user1061590 Avatar asked Dec 05 '11 02:12

user1061590


1 Answers

Yes, that's fine. As of C++03, vector is required to have contiguous storage.

As of C++11, the same is true for std::string, by the way; and you can say v.data() as a synonym for &v[0] (which is also valid when v is empty).

like image 173
Kerrek SB Avatar answered Sep 18 '22 15:09

Kerrek SB