Char * of std::vector<char> [duplicate]
Possible Duplicate:
Is it possible to get the pointer the continous memory fragment in a std::vector<char> in C++?
How do I开发者_如何学C get char*
from std::vector<char>
, just like the function std::string.c_str()
?
Take the adress of the first element:
char * foo = &my_vec[0];
To expand slightly on space_cowboy's answer...
You can do:
std::vector<char> vec;
vec.push_back('a');
vec.push_back('b');
vec.push_back('c');
char *arr = &vec[0];
However, if you were to now do a push_back
...
vec.push_back('d');
arr; // This pointer has been possibly invalidated!
// realloc could have been called on vec's memory.
精彩评论