将std :: string传递给函数f(** char) [英] Pass std::string to a function f(**char)
问题描述
是否可以将std :: string的指针传递给需要** 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;
有没有更短的路?很明显,s2.c_str()不工作,因为它返回 const * char
。
Is there no shorter way? It is obvious, that s2.c_str() does not work, since it returns const *char
.
推荐答案
这是处理这类函数的适当方法。你不能直接传递 std :: string
,因为你可以将它转换为C字符串,它在内存中的布局是不同的,所以被调用的函数不知道在哪里放它的结果。
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.
然而,如果可能,你应该重写函数,所以它需要一个 std: :string&
或 std :: string *
作为参数。
If possible, however, you should rewrite the function so it takes a std::string&
or std::string *
as an argument.
,请确保 free()
或 delete []
c $ c> f()是确定是否需要这样做。)
(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.)
这篇关于将std :: string传递给函数f(** char)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!