如下代码:上下两段计算出来的sizeof(*p)均为1,但是后面注释(不是我写的)为什么一个是contains a null character,一个是didn't contain null character? //string 转化为char* string str="good boy"; const char *p=str.c_str(); //contains a null character cout << str<< endl; cout << *p << sizeof(*p)<< endl; /*string str="good boy"; const char *p=str.data(); //didn't contain null character cout << str<< endl; cout << *p << sizeof(*p)<< endl; */ return 0;
c++ 字符串长度计算
- 写回答
- 好问题 0 提建议
- 追加酬金
- 关注问题
- 邀请回答
-
3条回答 默认 最新
- 水墨长天 2021-04-20 23:55关注
c_str()返回的指针指向null-terminated(字符串结束符'\0')的字符数组,即最后位置是一个null字符。
data()在C++11之前返回数组是不以'\0'结束的,在C++11之后功能和c_str()相同了。
原文参考链接:
https://en.cppreference.com/w/cpp/string/basic_string/c_str
Returns a pointer to a null-terminated character array with data equivalent to those stored in the string.
The pointer is such that the range
[c_str(); c_str() + size()]
is valid and the values in it correspond to the values stored in the string with an additional null character after the last position.https://en.cppreference.com/w/cpp/string/basic_string/data
The returned array is not required to be null-terminated.(until C++11)
The returned array is null-terminated, that is,
data()
and c_str() perform the same function.(since C++11)本回答被题主选为最佳回答 , 对您是否有帮助呢?解决 无用评论 打赏 举报
悬赏问题
- ¥15 stata安慰剂检验作图但是真实值不出现在图上
- ¥15 c程序不知道为什么得不到结果
- ¥40 复杂的限制性的商函数处理
- ¥15 程序不包含适用于入口点的静态Main方法
- ¥15 素材场景中光线烘焙后灯光失效
- ¥15 请教一下各位,为什么我这个没有实现模拟点击
- ¥15 执行 virtuoso 命令后,界面没有,cadence 启动不起来
- ¥50 comfyui下连接animatediff节点生成视频质量非常差的原因
- ¥20 有关区间dp的问题求解
- ¥15 多电路系统共用电源的串扰问题