在字符串中使用空字符(C+;+;) 我正在研究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; }

在字符串中使用空字符(C+;+;) 我正在研究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; },c++,string,arrays,null-character,C++,String,Arrays,Null Character,幕后发生了什么?为什么字符串文字和声明的字符数组将't'存储在索引6(在内部'\0'之后),而声明的字符串不存储?您正在从字符*构造一个字符串(或衰减到该值的东西)。这意味着C字符串的约定适用。也就是说,它们被'\0'终止。这就是为什么word2只包含“hello”据我记忆,前两个基本上只是一个数组,字符串的打印方式是继续打印,直到遇到\0为止。因此,在前两个示例中,您从字符串中第6个字符的点偏移开始,但在您的示例中,您正在打印第6个字符,即t string类的作用是将字符串复制到它自己的内部缓

幕后发生了什么?为什么字符串文字和声明的字符数组将
't'
存储在索引6(在内部
'\0'
之后),而声明的字符串不存储?

您正在从
字符*
构造一个字符串(或衰减到该值的东西)。这意味着C字符串的约定适用。也就是说,它们被
'\0'
终止。这就是为什么
word2
只包含
“hello”

据我记忆,前两个基本上只是一个数组,字符串的打印方式是继续打印,直到遇到
\0
为止。因此,在前两个示例中,您从字符串中第6个字符的点偏移开始,但在您的示例中,您正在打印第6个字符,即
t


string
类的作用是将字符串复制到它自己的内部缓冲区中,并将字符串从数组的开始复制到它找到的第一个
\0
。因此,
t
不会被存储,因为它位于第一个
\0

之后,因为采用
const char*
std::string
构造函数将其参数视为C样式字符串。它只是从中复制,直到找到空终止符,然后停止复制


最后一个例子实际上是调用未定义的行为
word2[6]
超过了字符串的末尾。

问题在于您根本没有打印字符串-您打印的是单个字符

char word [] = "hello\0there";//Array of char...
cout << word[6] << endl;      //So word[6] is the char't' (NOT a string)

string word2 = "hello\0there"; //std::string...
cout << word2[6] << endl;      //so word2[6] is the char 't' (NOT a string as well)
char-word[]=“你好\0这里”//字符数组。。。

当你打印所有3个表示形式时会发生什么?如果他也要打印,那么在
string
的情况下,你的索引超出了
string
的内存边界。幸运的是,你的代码没有崩溃。顺便说一句,如果他真的想复制整个字符串,他可以使用
std::string word3(“hello\0此处”,11)
char word [] = "hello\0there";//Array of char...
cout << word[6] << endl;      //So word[6] is the char't' (NOT a string)

string word2 = "hello\0there"; //std::string...
cout << word2[6] << endl;      //so word2[6] is the char 't' (NOT a string as well)
cout << &(word[6]) (char*, should print "there")
cout << &(word2[6]) (char* as well, undefined behaviour pre-C++11)