C"string"init - 哪个更好?

Sam*_*iew 2 c string

这两个初始化有什么区别?

char a[] = "string literal";

char *p  = "string literal";
Run Code Online (Sandbox Code Playgroud)

Mic*_*eyn 17

尽管两者看起来相似并且经常互换使用,但它们的确意味着不同的东西.第一行:

char a[] = "string literal"; 
Run Code Online (Sandbox Code Playgroud)

...创建一个足以容纳字符串文字的数组,包括其NUL终止符.它使用您指定的字符串文字初始化此数组.此版本的一个好处是可以在以后修改阵列.此外,即使在编译时也可以知道数组的大小,因此您可以使用sizeof运算符来确定其大小.例如:

printf("%u\n",unsigned(sizeof(a))); // Will display 15, which is the array's size 
                                    // including the NUL terminator
Run Code Online (Sandbox Code Playgroud)

第二行:

char *p  = "string literal"; 
Run Code Online (Sandbox Code Playgroud)

...只需设置一个指向字符串文字的指针.这比第一个版本更快,但是你有一个缺点,即不应该更改文字,因为它可能位于标记为只读的页面中.你还有一个缺点,即要知道字符串的长度,你需要使用该strlen()函数,因为sizeof操作符只会给你指针变量的大小.例如:

printf("%u\n",unsigned(sizeof(p))); // Will likely display 4 or 8, depending on
                                    // whether this is a 32-bit or 64-bit build
printf("%u\n",unsigned(strlen(p))); // Will display the correct length of 14, not
                                    // including the NUL terminator
Run Code Online (Sandbox Code Playgroud)

至于哪个更好,这取决于你将如何处理这些变量.如果您不需要对字符串进行任何更改,请使用更高版本,但更改char *为a const char *,以便您不会意外地尝试更改指向的字符.如果您打算更改数据,请使用以前基于阵列的版本,该版本允许您在初始化后对阵列进行更改.

  • 在第二个例子中使用`char const*'实际上更明智,但由于标准中的向后兼容疣,编译器必须接受`char*`版本. (2认同)