Kon*_*che 2 c++ string pointers
是否可以将std :: string的指针传递给期望**char的函数?函数需要**char才能为其写入值.
目前我正在做以下事情:
char *s1;
f(&s1);
std::string s2 = s1;
Run Code Online (Sandbox Code Playgroud)
有没有更短的方式?很明显,s2.c_str()不起作用,因为它返回const *char.
这是处理这种功能的适当方式.你不能std::string直接传入,因为虽然你可以将它转换为C字符串,但它在内存中的布局不同,因此被调用的函数不知道将结果放在何处.
但是,如果可能的话,您应该重写该函数,以便它需要一个std::string&或std::string *一个参数.
(另外,如果合适,请确保您free()或delete[]C字符串.请参阅文档f()以确定是否需要执行此操作.)