Passing a vector std :: string to char ***

I have an API function that expects a char*** parameter and wants to pass vector<std::string> . Are there any member functions from std::string that allow me to do this?

This way I get only the char pointer to the first element:

 std::vector<std::string> oList(128); myFunction(oList[0].c_str()); 
0
source share
2 answers

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

In short: No.

The fact that std::vector<std::string> stores instances of std::string in an adjacent array does not mean that pointers to the base char arrays of these string instances appear in memory.

+4
source

It is not possible to pass the entire vector to an array of pointer pointers. You can handle the active part of vector as if it were an array of vector elements, but in this case it would be an array of string objects, not a pointer to char* . Trying to interpret it as anything else will be undefined.

If you are sure that the API will not touch the contents of char* strings (for example, since it is const -qualified), you can create an array of pointers and put the results of calls in c_str() on vector elements in it, for example:

 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 when passing an array of APIs that uses an extra level of indirection, because changing the pointer you pass may require the third asterisk to change, for example, reallocating the array. In this case, you may need to use a different mechanism for allocating dynamic memory according to the mechanism used by your API.

+4
source

Source: https://habr.com/ru/post/983748/


All Articles