小编Joh*_*ney的帖子

C++ char数组null终止符位置

我是一名学习C++的学生,我试图理解空终止字符数组是如何工作的.假设我定义了一个char数组,如下所示:

char* str1 = "hello world";
Run Code Online (Sandbox Code Playgroud)

正如预期的那样,strlen(str1)等于11,并且它以空值终止.

如果上面的char数组的所有11个元素都填充了字符"hello world",那么C++在哪里放置null终止符?它实际上是分配一个长度为12而不是11的数组,第12个字符是'\0'CPlusPlus.com似乎建议11中的一个需要'\0',除非它确实分配12.

假设我执行以下操作:

// Create a new char array
char* str2 = (char*) malloc( strlen(str1) );

// Copy the first one to the second one
strncpy( str2, str1, strlen(str1) );

// Output the second one
cout << "Str2: " << str2 << endl;
Run Code Online (Sandbox Code Playgroud)

这个输出Str2: hello worldatcomY?°g??,我假设是C++在指针指向的位置读取内存,char* str2直到它遇到它解释为空字符的内容.

但是,如果我这样做:

// Null-terminate the second one
str2[strlen(str1)] = '\0';

// Output the second one …
Run Code Online (Sandbox Code Playgroud)

c++ arrays char null-terminated

13
推荐指数
2
解决办法
3万
查看次数

标签 统计

arrays ×1

c++ ×1

char ×1

null-terminated ×1