【发布时间】: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);
【问题讨论】: