我想将一个字符绑定(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(...)
重新分配缓冲区打电话。
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
andstring::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/