Cast a vector of std::string to char***
Asked Answered
P

2

0

I have an API function that expects a char*** parameter and want to pass a vector<std::string>. Are there member functions of std::string that let me do that?

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

std::vector<std::string> oList(128);
myFunction(oList[0].c_str());
Prosthodontics answered 29/12, 2014 at 11:12 Comment(1)
Why does the API need the third level of indirection? A vector of strings should be char**, not char***.Iceland
C
4

"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.

Cresol answered 29/12, 2014 at 11:17 Comment(0)
I
4

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.

Iceland answered 29/12, 2014 at 11:31 Comment(3)
Why the hell do you use a C arrays for that?! What happens if myTrippleStarFunction() can throw??Columnar
And what if the function called calls free() on the pointer?? If it's taking a char***, it's likely a C API, after all. Really, this question is way to vague to answer it meaningfully.Columnar
Well, yes, you can do it – by posting horrific code that prompts what's obviously a complete novice to use manual memory management, and which – given that we do not know what the API needs a pointer to a pointer to a pointer to a non-const string for – is at least as likely to blow up in the OP's face as it is to actually solve the problem.Columnar

© 2022 - 2024 — McMap. All rights reserved.