现在的位置: 首页 > 综合 > 正文

45、c_str与data()

2012年07月19日 ⁄ 综合 ⁄ 共 805字 ⁄ 字号 评论关闭

c_str()返回的指针保证指向一个size()+1长的空间,而且最后一个字符肯定'\0'。而data返回的指针则保证指向一个size()长度的空间,有没有null-terminate不保证,可能有,可能没有,看库的实现了。

c_str()返回的是C风格的字符串的首地址,而data()返回的是字符数组的首地址。

    程序中,只在需要时才使用c_str()或者data()得到字符串,每调用一次,下次再使用就会失效。【3

1、const char* c_str ( ) const;

Generates a null-terminated sequence of characters (c-string) with the same content as the string object and returns it as a pointer to an array of characters.

A terminating null character is automatically appended.

2、const char* data() const;

Returns a pointer to an array of characters with the same content as the string.

Notice that no terminating null character is appended

3、一般,我们需要字符串转换时用c_str(),处理二进制数据时用data()

1http://topic.csdn.net/u/20070120/01/d74734b8-04a7-4ab9-bab8-2ab875b608df.html

2http://blog.csdn.net/feelang/article/details/6338757

3http://www.cnblogs.com/lancidie/archive/2011/03/17/1987130.html

4cplus官网

抱歉!评论已关闭.