Possible Duplicate:
std::vector<std::string> to char* array
I have to call a c function that accepts an array of string pointers. Example
void cFunction(char* cities[], int count)
{
for(int i = 0; i < count; ++i )
{
printf("%s\n", cities[i]);
}
}
Assume that function is in some third party libabry; it cannot be changed
I can declare a static array and call the function like this
char* placesA[] = {"Teakettle Junction", "Assawoman Bay", "Land O' Lakes", "Ion", "Rabbit Hask" };
cFunction(placesA, 5);
That works. But my data is dynamic i.e. the size of the array changes many times at runtime
So I tried this
std::vector<std::string> placesB(placesA, placesA + 5);
cFunction(&placesB[0], 5); // this won't work because std::string != char*[]
Tried this
std::vector<char*> placesC;
cFunction(&placesC[0], 5);
I find placesC awkward to populate at the sametime avoid memory leaks
I am looking for a solution that is both efficient ( as little string copying as possible and preferably uses STL and or Boost )
There’s going to be some awkwardness no matter how you slice it. If the C API truly requires modifiable arrays, then that’s what you’ll need to provide — you’ll have to copy your strings into. If it doesn’t modify the strings, then you can use a
std::vectorofconst char*, where the string data is still owned by the underlyingstd::stringobjects; you just have to be careful that the C API doesn’t hold onto references to those strings and tries to access them after the strings have been modified or deallocated.For example, here’s one way to do it: