c++ - 将 char* 绑定(bind)到字符串

标签 c++ string bind c-strings

我想将一个字符绑定(bind)到一个字符串,但我不知道该怎么做: 我的想法是我有一个函数 void f(char mychar)* 可以更新 mychar 的值。我想将此更新传递到一个字符串中。

代码必须如下所示:

char* mychar = new char[128];

string mystring;

\\bind mystring with mychar
.....

f(mychar);

std::cout << mychar << std::endl ;
std::cout << mystring << std::endl

并且mychar和mystring返回的值必须相同。

有什么想法吗?

非常感谢。

最佳答案

一个字符串可以改变它的内部缓冲区,所以即使你可以创建一个使用特定缓冲区的字符串,在常见的突变之后,它也可能有一个不同的后备缓冲区。

例如,它可以根据 string::reserve(...) 重新分配缓冲区打电话。

string::c_str

The pointer returned points to the internal array currently used by the string object to store the characters that conform its value.

Both string::data and string::c_str are synonyms and return the same value.

The pointer returned may be invalidated by further calls to other member functions that modify the object.

C++98 的注释有这个警告

A program shall not alter any of the characters in this sequence.

您似乎希望 f(mychar) 执行此操作。

关于c++ - 将 char* 绑定(bind)到字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29147967/

相关文章:

C++语法解释

c++ - boost::asio,异步读取错误

c++ - 无法在 OpenCV 中使用 imwrite 写入图像

java - 读取文本文件并比较文本 - Java

php - 自动分配 PDO 类型

javascript - 在事件上使用 jQuery 时执行 JavaScript 函数

php - 谁能帮我如何在字符串中绑定(bind)变量?

c++ - 结束迭代器递减的可移植性如何?

java - 我如何使用java编写remove方法?

C++:二叉搜索树适用于整数,但在我尝试传递字符串时崩溃