【发布时间】:2012-07-20 15:27:27
【问题描述】:
我正在复习我的 C++,偶然发现了一个关于字符串、字符数组和空字符 ('\0') 的奇怪行为。以下代码:
#include <iostream>
using namespace std;
int main() {
cout << "hello\0there"[6] << endl;
char word [] = "hello\0there";
cout << word[6] << endl;
string word2 = "hello\0there";
cout << word2[6] << endl;
return 0;
}
产生输出:
> t
> t
>
幕后发生了什么?为什么字符串字面量和声明的 char 数组在索引 6 处存储了't'(在内部 '\0' 之后),而声明的字符串却没有?
【问题讨论】:
-
当您
cout << word2时会发生什么?这可能会让您深入了解正在发生的事情。 -
@philipvr 打印所有 3 个表示只生成字符串“hello”。
-
如果他是
cout << word2,它会打印出hello,这并不能真正说明他的问题。
标签: c++ string arrays null-character