char * of std :: vector <char> </char>

时间:2011-05-24 05:45:20

标签: c++

  

可能重复:
  Is it possible to get the pointer the continous memory fragment in a std::vector<char> in C++?

如何从char*获取std::vector<char>,就像函数std::string.c_str()一样?

2 个答案:

答案 0 :(得分:5)

取第一个元素的地址:

char * foo = &my_vec[0];

答案 1 :(得分:1)

稍微扩展一下space_cowboy的回答......

你可以这样做:

std::vector<char> vec;
vec.push_back('a');
vec.push_back('b');
vec.push_back('c');

char *arr = &vec[0];

但是,如果您现在要做push_back ...

vec.push_back('d');
arr; // This pointer has been possibly invalidated!
     // realloc could have been called on vec's memory.