Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pass std::string to a function f(**char)

Is it possible to pass the pointer of a std::string to a function which expects a **char? The function expects a **char in order to write a value to it.

Currently I am doing the following:

char *s1;
f(&s1);
std::string s2 = s1;

Is there no shorter way? It is obvious, that s2.c_str() does not work, since it returns const *char.

like image 561
Konrad Reiche Avatar asked Oct 26 '25 18:10

Konrad Reiche


1 Answers

That's the appropriate way to handle that sort of function. You cannot pass in the std::string directly because, while you can convert it to a C string, it is laid out in memory differently and so the called function would not know where to put its result.

If possible, however, you should rewrite the function so it takes a std::string& or std::string * as an argument.

(Also, make sure you free() or delete[] the C string if appropriate. See the documentation for whatever f() is to determine if you need to do so.)

like image 165
Jonathan Grynspan Avatar answered Oct 28 '25 06:10

Jonathan Grynspan