字符串文字是常量吗? [英] Are string literals const?
问题描述
如果我将字符串文字分配给 char*
,GCC 和 Clang 都不会抱怨,即使使用了很多迂腐的选项(-Wall -W -pedantic -std=c99
):
Both GCC and Clang do not complain if I assign a string literal to a char*
, even when using lots of pedantic options (-Wall -W -pedantic -std=c99
):
char *foo = "bar";
虽然他们(当然)会抱怨如果我将 const char*
分配给 char*
.
while they (of course) do complain if I assign a const char*
to a char*
.
这是否意味着字符串文字被视为 char*
类型?它们不应该是 const char*
吗?如果它们被修改,这不是定义的行为!
Does this mean that string literals are considered to be of char*
type? Shouldn't they be const char*
? It's not defined behavior if they get modified!
并且(一个不相关的问题)命令行参数(即:argv
)怎么样:它是否被认为是字符串文字数组?
And (an uncorrelated question) what about command line parameters (ie: argv
): is it considered to be an array of string literals?
推荐答案
它们属于 char[N]
类型,其中 N
是字符数,包括终止 <代码> 代码>.所以是的,您可以将它们分配给 char*
,但您仍然无法写入它们(效果将是未定义的).
They are of type char[N]
where N
is the number of characters including the terminating