第一个创建一个指向字符串文字的指针"hello"
,它可能存储在程序的可执行映像中的不可写内存中。即使不是,您也不允许修改该数组的内容。
The second one creates an automatic array1 (on the stack (usually, but that is implementation-defined)) and initialises it with the string "goodbye"
. It is equivalent to
char const b[] = {'g', 'o', 'o', 'd', 'b', 'y', 'e', 0};
So while "goodbye"
is immutable because it is a string literal which is char const[8]
and stored in non-writable memory, the array b
is an automatic1 array that is immutable because you marked it const
, but you could remove the const
from the variable declaration to make the array's contents mutable. You are only initialising the contents of the array with the contents of the array "goodbye"
.
您不能修改其中任何一个,因为它们都是const char[]
,但第二个可以改为char[]
是可变的,而第一个则不能。
请参阅此答案以获取更多信息:https://stackoverflow.com/a/9106798/726361
1 As R. Martinho Fernandes pointed out in the comments, the syntax T x[] = ...
could also create a static array (not automatic but static (in the executable image usually, but that's implementation defined)) if it is at namespace scope, and it's only an automatic array otherwise.