将std::string传递给函数f(**char)
Pass std::string to a function f(**char)
是否有可能将std::string的指针传递给期望**char的函数?该函数需要一个**字符,以便向其写入值。
当前我正在做以下操作:
char *s1;
f(&s1);
std::string s2 = s1;
没有更近的路吗?很明显,s2.c_str()不起作用,因为它返回const *char
.
这是处理这类函数的合适方法。您不能直接传入std::string
,因为虽然您可以将转换为C字符串,但它在内存中的布局不同,因此被调用的函数不知道将其结果放在哪里。
但是,如果可能的话,您应该重写该函数,使其接受std::string&
或std::string *
作为参数。
(另外,如果合适的话,请确保free()
或delete[]
为C字符串。请参阅f()
的文档,以确定您是否需要这样做。
不,那不可能。函数覆盖指针(s1)本身。您可以从字符串(&s2[0])传入数据数组,但这只允许您覆盖当前保留的内容空间,而不是指针。
函数还以某种方式为字符串分配内存。你可能也需要清理一下。如果它起作用了,它将如何被清理?
你不能——字符串的字符缓冲区是不可写的,你不应该这样做。您总是可以使用中间缓冲区:
const size_t n = s2.size();
char buf[n + 1];
buf[n] = 0;
std::copy(s2.begin(), s2.end(), buf);
f(&buf);
s2.assign(buf, n);
是的,写一个包装器函数/宏,然后使用它
将字符串传递给函数的一种方法是让字符串
std::string name;
作为对象的数据成员。然后,在f()
函数中创建一个字符串,并像前面所示的那样通过引用传递它
void f( const std::string & parameter_name ) {
name = parameter_name;
}
现在,要将字符串复制到char *,以便将其作为char引用传递给函数:
从这个链接:
如果你想获得一个可写的副本,比如str.c_str()
,比如char *,你可以这样做:
std::string str;
char * writable = new char[str.size() + 1];
std::copy(str.begin(), str.end(), writable);
writable[str.size()] = ' '; // don't forget the terminating 0
// don't forget to free the string after finished using it
delete[] writable;
上面的不是异常安全的!
您可以通过引用将char * writable
传递给f()
函数。
相关文章:
- 将char*传递给pthread_read函数
- 为什么这个函数将"const char*"转换为"void* const"而不是"const void*"
- 从函数返回const char*数组
- 在没有定义返回类型的函数中返回布尔值,并将结果保存在无错误的char编译中-为什么
- 使用c#访问c++dll中带有char*参数的函数时发生AccessViolationException
- 将函数参数"const char*"转换为"std::string_view"是
- std::string 构造函数如何处理固定大小的 char[]?
- 在 constexpr 构造函数 (c++17) 中赋值到 const char * 在使用 Android NDK 时
- 构造函数 (C++) 中的 char 指针参数存在问题
- c ++ 如何在构造函数中初始化 char
- C++ 存储来自 char* 函数的字符列表
- 从循环返回char函数数据
- 预处理器检查 constexpr const char* 函数
- 如何使const char*函数起作用
- 返回一个带有随机选项和局部变量的 char 函数
- System::字符串到char*函数.内存泄漏
- 如何在c++中使用递归char *函数来反转字符串
- 如何在c++中创建一个char函数
- Windows与UTF-16一起使用char*函数
- c++在char函数中搜索char