【问题标题】:Null terminated character array vs string object空终止字符数组与字符串对象
【发布时间】:2015-08-13 08:16:20
【问题描述】:

我是 C++ 新手,我正在深入研究 char 数组和字符串对象。我读到 char 数组以字符 '\0' 为空终止,并且字符串对象不是空终止,除非您使用字符串库的成员函数 c_str()。这里我有一些代码,我希望我的第一个循环永远运行,但它们都迭代了大约 6 次。请原谅我可怜的变量名称,但有人可以向我解释为什么字符串对象不会导致无限循环。

我在想任何被索引但尚未分配值的内存位置已经由 char '\0' 表示。如果是这样,请告诉我。

std::string is_terminated = "string";
char is_t[] = "string";

int i = 0;
while (is_terminated[i] != '\0') {
    std::printf("Element at index %d is %c\n", i, is_terminated[i]);
    i++;
}
std::printf("Times ran: %d\n", i);

int j = 0;
while (is_t[j] != '\0') {
    std::printf("Element at index %d is %c\n", j, is_t[j]);
    j++;
}
std::printf("Times ran: %d\n", j);

【问题讨论】:

    标签: c++ c++11


    【解决方案1】:

    虽然std::string 不一定存储'\0'(它是实现定义的),但operator[](size_type pos)pos == size() 时返回空字符。

    【讨论】:

    • 你怎么能确定std::string最后没有实际存储'\0'?不是实现定义的吗?
    • @Mikhail 你说得对;我指的是公共界面。
    • @Mikhail: 概念上它没有被存储,因为所有“序列容器操作”(例如通过begin()/end()遍历字符串,添加一个字符通过push_back 等)表现得“好像”\0 不存在。
    • @MatteoItalia,当然,conceptually,但我写的是 actually :) 我不太确定,actually i> hapens,我不知道这个空字符是否保留在字符串的末尾。至少我希望std::string 总是有足够的容量在c_str() 的调用中快速添加它。
    • @BoPersson: *(&s[0] + s.size())
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-04-01
    • 2012-08-14
    • 2011-06-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多