Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the most efficient way to convert STL string array to const char* array?

We have:

 std::string string_array[2];

 string_array[0] = "some data";

 string_array[1] = "some more data";

 char* cstring_array[2];

What is the most efficient way to copy data from string_array to cstring_array? Or pass string_array to the function, needed "const char* cstring_array[]"?

like image 874
hoxnox Avatar asked Feb 17 '26 06:02

hoxnox


2 Answers

A function that takes a char const * is only written to accept a single string at a time, not an array of strings. To pass an std::string to such a function, just call the function with your_string.c_str() as the parameter.

Edit: for a function that takes an array of strings, the obvious choice (at least to me) would be to write a minimal front-end that lets you pass a vector<std::string>:

// The pre-existing function we want to call.
void func(char const *strings[], size_t num) { 
    for (size_t i=0;i<num; i++)
        std::cout << strings[i] << "\n";
}

// our overload that takes a vector<string>:
void func(std::vector<std::string> const &strings) { 
    std::vector<char const *> proxies(strings.size());

    for (int i=0; i<proxies.size(); i++)
        proxies[i] = strings[i].c_str();
    func(&proxies[0], proxies.size());
}
like image 113
Jerry Coffin Avatar answered Feb 19 '26 19:02

Jerry Coffin


Use string::c_str to get const pointer to a char.

like image 34
Kirill V. Lyadvinsky Avatar answered Feb 19 '26 18:02

Kirill V. Lyadvinsky