且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

将向量std :: string转换为char ***

更新时间:2022-05-31 06:00:45

无法将整个向量强制转换为指针数组.您可以将vector的活动部分视为向量元素的数组,但是在这种情况下,它将是string对象的数组,而不是指向char*的指针.试图将其重新解释为其他内容将是不确定的.

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.

如果您确定API不会触及char*字符串的内容(例如,因为它是const限定的),则可以制作一个指针数组,并将调用结果放入c_str()放在vector的元素上,就像这样:

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;

但是,您需要非常小心地将类似的数组传递给使用额外间接级别的API,因为它可能需要第三个星号来更改传递的指针,例如,通过重新分配数组.在这种情况下,您可能必须使用其他机制分配动态内存以匹配您的API使用的机制.

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.