C 数组初始化 - 一些基础知识

标签 c arrays string initialization string-literals

我在一本书上读到,当你有一个像这样的字符串"blabla",这意味着有一个隐藏的字符数组,这个表达式返回第一个地址元素,它就像一个常量数组。

这让我对两种情况感到困惑:

  1. char a[7] = "blabla" ,是不可能的,因为 "blabla"返回一个 address 到数组的第一个元素,那么如何将地址放入 a 而不是实际元素?

  2. 它说,当您看到“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/

相关文章:

c++ - 在 g++ 中使用 __attribute__ 的不平衡括号

c - 在 C 中使用 strtok 解析输入

javascript - 如何跳过两个相同数组索引之间的比较?

string - 使用正则表达式从字符串中提取日期

c++ - 如何从字符串 vector 中选择第n个位置?

c++ - 我的动态数组模板类在做奇怪的事情

c - 函数获取单词并将它们放入数组中

c - 尝试填充结构数组时发生访问冲突

c - Mac OS X,如何为ARM编译.c文件并在之后反汇编它?