There is a function that needs a const char* array, basically a list of words. Because this list of word can change, I can not declare and initalize this array at program start. For now, I have a vector of strings and I need to convert this to an array of const char*. How can this be done? Thanks!
Example:
std::vector<std::string> list;
list.push_back("word1");
list.push_back("word2"); // and so on...
const char* wordList[] = ???
No matter what, you'll hit some complicated lifetime issues, but I think this is the simplest way:
std::vector<const char*> ptrs;
for (std::string const& str : list) {
ptrs.push_back(str.data());
}
If you need your const char**
, you can call ptrs.data()
. The issue, of course, is that ptrs
and list
must both stay alive for ptrs.data()
to be valid.
Another thing to watch out for is that if you push_back
more elements to list
, then list
could reallocate, which would invalidate the pointers in ptrs
.
You can't convert it, but it's straightforward to create an array:
std::vector<const char*> strings;
for (int i = 0; i < list.size(); ++i)
strings.push_back(list[i].c_str();
And now, strings.data()
gives you an array of const char*
.
Note that strings
should not be used after list
has been destroyed, since it holds pointers to data that lives in list
. I'd probably wrap this in a function:
void call_C_function(const std::vector<std::string>& list) {
std::vector<const char*> strings;
for (int i = 0; i < list.size(); ++i)
strings.push_back(list[i].c_str());
c_function(strings.data());
}
That way, strings
will live only through the call to c_function
, and there is no danger of it outlasting list
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With