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[]"?
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());
}
Use string::c_str to get const pointer to a char.
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