The API expects an array of zero-terminated c-strings (char*). The array itself is to be terminated with a null pointer (nullptr).
1 Answer
How about using std::transform?
#include <iostream> #include <string> #include <vector> #include <algorithm> int main() { std::vector<std::string> v = {"asd","qwe"}; const char** c = new const char*[v.size()]; std::transform(v.begin(), v.end(), c, [](const std::string& s) { return s.c_str(); }); for (size_t i=0;i<v.size();i++) { std::cout << c[i] << std::endl; } delete[] c; return 0; } But do mind that the array(here c) should be in the same scope as the vector(here v) or the vector should not get destroyed before the use of the array(c) is over.
If you want a char** instead and not const char**, you can use .data() instead of .c_str()
4 Comments
HolyBlackCat
You don't have to allocate the array manually. I'd use
std::vector<const char *> s;.theWiseBro
@HolyBlackCat and then use s.data() to access the underlying data?
HolyBlackCat
@theWiseBrо Yep.
MaxSyndow
@@theWiseBrо @HolyBlackCat Yeah, using new and delete directly is sloppy C++.
char*. Each of thesechar*will point to a null-terminated string except the last entry in the array. The last entry in the array isnullptrso that the size of the array does not need to be passed around. (I've seen this interface before, but I forget where.)