Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to convert "std::vector<std::string>" to "const char* array"? [duplicate]

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[] = ???
like image 233
Lemonbonbon Avatar asked Feb 04 '19 15:02

Lemonbonbon


2 Answers

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.

like image 111
hegel5000 Avatar answered Oct 24 '22 10:10

hegel5000


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.

like image 31
Pete Becker Avatar answered Oct 24 '22 11:10

Pete Becker