在第二个中,您正在制作副本。起初你不是。
char str[] = {'h','e','l','l','o',' ','w','o','r','l','d','\0'};
这里str 是在堆栈上创建的数组。正在向str 复制内容。怎么过-
char *str = "hello word";
str 指向驻留在不可修改部分的数据。所以,你不能当尝试结果分段错误。
cmets 说明
我不认为,因为原始数据类型 C 和 C++ 会改变它的规则。来自 ISO/IEC 14882:2003(E),第 8.5.2 节
1. A char array (whether plain char, signed char, or unsigned char) can be
initialized by a string- literal (optionally enclosed in braces); a wchar_t
array can be initialized by a wide string-literal (option- ally enclosed in
braces); successive characters of the string-literal initialize the members of
the array.
[Example:
char msg[] = "Syntax error on line %s\n"; shows a character array
whose members are initialized with a string-literal. Note that because
’\n’ is a single character and because a trailing ’\0’ is appended,
sizeof(msg) is 25.
]
2. There shall not be more initializers than there are array elements.
[Example:
char cv[4] = "asdf" ;// error is ill-formed since there is no space for the implied trailing ’\0’.
]
因此,示例 2 消除了疑问。