13

I want to access starting address of the array that is maintained by the string class.

string str="hey";
char* pointer=(char*)str.c_str();
  1. Is the pointer pointing to the address of the array(maintained by the string class)? or string class will create a new array from dynamic memory and copy the existing string into it and return it's address?

  2. If this is not the right way, then how to access the starting address of the array that is maintained by the string class?

4

5 回答 5

30

C++11标准中,明确规定.c_str()(以及更新.data()的 )应返回指向std::string.

在通过获取指针后对 std::string 的任何修改都.c_str() 可能导致所述char *返回变得无效(即 - 如果std::string内部必须重新分配空间)。

在以前的 C++ 标准实现中允许返回任何东西。但作为标准不要求用户解除分配结果,我从未见过任何实现返回任何新分配的内容。至少 GNU gcc 和 MSVC++ 的 STL 字符串是内部以零结尾的字符数组,由c_str().

因此可以安全地假设(对于 C++ 而言,通常要谨慎)在任何 C++ 版本中的任何实现中.c_str()都将返回内部缓冲区。

换句话说,.c_str()除非你 100% 确定它不会在未来的任何时候改变它的大小(除非它是 a const,否则你永远不应该保留它的值)。

PS顺便说一句,你永远不应该这样做char* pointer=(char*)str.c_str();。它是const char *并且您不应修改内容,部分原因是上述情况-您最终可能会覆盖其他对象的内存破坏 的内部状态std::string,以防实现做一些花哨的事情,例如更快地索引字符.find()(较新看到的,但是嘿- 这是一个封装!)

于 2013-07-01T11:18:16.607 回答
4

注意:我的回答只对pre-C++11是正确的。对于 C++11,是正确的答案。


  1. 它返回一个以空结尾的 C 字符串。std::string它本身不是以 null 结尾的,因此允许(并且可能会)返回一个新分配的const char. 如果创建std::string超出范围或发生变异,则c_str()-returned 字符串无效。

  2. data()返回数据,但请注意它不是以 null 结尾的字符串。

在这两种情况下,您都应该调整该数据data()c_str()返回指向 的指针const char,而您确实不应该这样做。

例如,std::string允许 s 是引用计数的字符串(尽管这不再常见),或者甚至可以在其数据上使用时髦的索引方案(尽管从未见过)。

于 2013-07-01T11:10:10.340 回答
1

您可以通过 获取字符串的起始地址char *address = &str[0];。无需将字符串转换为 c 字符串表示形式。

于 2013-07-01T11:06:58.230 回答
1

如果您真的想要字符串中的“数据”,那么string::data()就是您要查找的函数。

但是请注意,likec_str()const指向数据的指针 - 您不应该修改此数据。

于 2013-07-01T11:11:14.027 回答
0

在 C++11 中,返回的指针指向字符串对象当前用于存储符合其值的字符的内部数组。

有关详细信息,请参阅http://www.cplusplus.com/reference/string/string/c_str/

于 2013-07-01T11:08:47.133 回答