Cast a vector of std::string to char***

夙愿已清 提交于 2019-12-02 11:01:29

"Are there member functions of std::string that let me do that?"

In short: No.

That std::vector<std::string> stores the std::string instances in a contiguous array, doesn't mean that the pointers to the underlying char arrays of these string instances appear contiguously in memory.

There is no way to cast the entire vector to an array of pointers to pointers. You can treat the active portion of the vector as if it were an array of vector's elements, but in this case that would be an array of string objects, not pointers to char*. Trying to re-interpret it as anything else would be undefined.

If you are certain that the API is not going to touch the content of char* strings (for example, because it is const-qualified) you could make an array of pointers, and put results of calls to c_str() on vector's elements into it, like this:

char **pList = new char*[oList.size()];
for (int i = 0 ; i != oList.size() ; i++) {
    pList[i] = oList[i].c_str();
}
myTrippleStarFunction(&pList); // Use & to add an extra level of indirection
delete[] pList;

However, you need to be very careful passing an array like that to an API that uses an extra level of indirection, because it may need that third asterisk to change the pointer that you pass, for example, by reallocating the array. In this case you might have to use a different mechanism for allocating dynamic memory to match the mechanism used by your API.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!