Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/cplusplus/159.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C++ 以空结尾的字符串_C++ - Fatal编程技术网

C++ 以空结尾的字符串

C++ 以空结尾的字符串,c++,C++,以下哪项是以null结尾的字符串 char *str1 = "This is a string."; char *str2 = "This is a string.\0"; char str3[] = "This is a string."; const char *str4 = "This is a string."; const char *str5 = "This is a string.\0"; const char str6[] = "This is a string."; 它们都是

以下哪项是以null结尾的字符串

char *str1 = "This is a string.";
char *str2 = "This is a string.\0";
char str3[] = "This is a string.";
const char *str4 = "This is a string.";
const char *str5 = "This is a string.\0";
const char str6[] = "This is a string.";

它们都是以null结尾的(
str2
str5
实际上是以双null结尾的),因为使用双引号是以null结尾的字符数组的缩写

因此:

"Hello"
实际上是这样的:

{'H', 'e', 'l', 'l', 'o', '\0'}
指向此类字符串文本的变量应声明为
const

  • All:字符串文字是以null结尾的字符串
  • str2
    str5
    具有双重空终止字符串的特殊性
此外:

  • char*str1
    应该是
    const char*str1
  • char*str2
    应该是
    const char*str2

    • 全部。C编译器自动聚合带有终止符“\0”的字符串,然后将其存储在char[]中或通过char*引用它

      如果您想对字符串执行某些操作,例如修改它,或者即使您想将某些内容连接到它,也不要使用
      char*s=“hi”
      ,因为这里的字符串
      hi
      位于内存的只读部分,并且您的程序可能会崩溃

      最后一个字符串(str3)是错误的。这是一个有效的数组初始化。“我总是以null结尾。”