我在一本书上读到,当你有一个像这样的字符串"blabla"
,这意味着有一个隐藏的字符数组,这个表达式返回第一个地址元素,它就像一个常量数组。
这让我对两种情况感到困惑:
char a[7] = "blabla"
,是不可能的,因为 "blabla"返回一个 address 到数组的第一个元素,那么如何将地址放入a
而不是实际元素?它说,当您看到“blabla”时,它表示像一个
const
字符数组,这意味着我根本无法更改a
(这不是真的)。
我想我不清楚这里真正基本的东西。
最佳答案
根据 C 标准(6.3.2.1 左值、数组和函数指示符)
3 Except when it is the operand of the sizeof operator or the unary & operator, or is a string literal used to initialize an array, an expression that has type ‘‘array of type’’ is converted to an expression with type ‘‘pointer to type’’ that points to the initial element of the array object and is not an lvalue. If the array object has register storage class, the behavior is undefined.
所以在这个声明中
char a[7] = "blabla";
具有字符数组char[7]
类型的字符串文字的元素由于包含终止零作为字符串文字的元素而用于初始化字符数组的元素一个
其实这个声明等同于声明
char a[7] = { 'b', 'l', 'a', 'b', 'l', 'a', '\0' };
请注意,在 C 中,字符串文字具有非常量字符数组的类型。然而,它们本身可能是不可修改的。
来自 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 = "blabla";
在这种情况下,根据 C 标准的第一条引述,字符串文字被转换为指向其第一个元素的指针,指针的值被分配给变量 s
。
即在静态内存中创建了一个未命名的字符数组,并将数组第一个元素的地址分配给指针s
。例如,您不能使用指针来更改您可能不会编写的文字
char *s = "blabla";
s[0] = 'B';
在 C++ 中,字符串文字确实具有常量字符数组类型。所以你必须在 C++ 程序中编写
const char *s = "blabla";
在 C 中你也可以这样写
char a[6] = "blabla";
^^^^
在这种情况下,字符串文字的终止零将不会用于初始化字符数组 a
。因此该数组将不包含字符串。
在 C++ 中这样的声明是无效的。
关于C 数组初始化 - 一些基础知识,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44175432/