字符串文字是常量吗? [英] Are string literals const?

查看:31
本文介绍了字符串文字是常量吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我将字符串文字分配给 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 . So yes you can assign them to char*, but you still cannot write to them (the effect will be undefined).

Wrt argv:它指向一个指向字符串的指针数组.这些字符串是可显式修改的.您可以更改它们,它们需要保存最后存储的值.

Wrt argv: It points to an array of pointers to strings. Those strings are explicitly modifiable. You can change them and they are required to hold the last stored value.

这篇关于字符串文字是常量吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆