c - 数组是变量还是常量?

标签 c arrays pointers variables constants

我只想知道:数组在C中是变量还是常量?

我对字符数组特别困惑。

最佳答案

根据 C 标准(6.3.2.1 左值、数组和函数指示符)

1 An lvalue is an expression (with an object type other than void) that potentially designates an object;64) if an lvalue does not designate an object when it is evaluated, the behavior is undefined. When an object is said to have a particular type, the type is specified by the lvalue used to designate the object. A modifiable lvalue is an lvalue that does not have array type, does not have an incomplete type, does not have a constqualified type, and if it is a structure or union, does not have any member (including, recursively, any member or element of all contained aggregates or unions) with a constqualified type.

所以数组是不可修改的左值。那就是你可能不会写例如

char s1[] = "hello";
char s2[] = "hello";

s1 = s2;

编译器将发出代码无效的诊断消息。

至于字符串文字,它们具有静态存储持续时间,任何修改字符串文字的尝试都会导致未定义的行为。

来自 C 标准(6.4.5 字符串文字)

7 It is unspecified whether these arrays are distinct provided their elements have the appropriate values. If the program attempts to modify such an array, the behavior is undefined.

比较这两个代码片段。

char s[] = "hello";
s[0] = 'H';

char *s = "hello";
s[0] = 'H';

在第一个代码片段中,声明了一个由字符串文字初始化的字符数组。即字符串文字的字符用于初始化数组的元素。您可以更改创建的数组。

在第二个代码片段中,声明了一个指向 strig 文字的指针。在第二条语句中,尝试使用导致未定义行为的指针更改字符串文字。

至于像 const 限定符 then (6.7.3 类型限定符)这样的限定符

9 If the specification of an array type includes any type qualifiers, the element type is so qualified, not the array type. If the specification of a function type includes any type qualifiers, the behavior is undefined

所以这个声明

const char s[] = "hello";

表示数组的每个元素在其类型规范中都具有限定符 const,即每个元素都具有类型 const char

关于c - 数组是变量还是常量?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45236602/

相关文章:

c - C中指向多维​​数组的指针?

c - 在 C 中写入超出数组末尾的内容

c++ - 在 C++ 中将项目添加到列表

java - 如何删除字符串中的多余空格和新行?

javascript - javascript中的for循环以增量方式访问元素

swift - 如何使用 Parse in swift 从指针内部的指针访问值?

c++ - node* 和 node*& c++ 之间的区别

c - struct中的char []和char *有什么区别?

c - 运行代码时它没有响应(但它在后台正确运行)

php - 引用 - 这个错误在 PHP 中意味着什么?