c - 什么是c中的数组衰减以及它何时发生?

标签 c arrays pointers implicit-conversion

我目前正在学习C语言。 我想知道“数组衰减”是什么意思,以及它何时发生。

我想知道下面的两个变量是否以相同的方式解释。


char(*zippo)[2] = NULL;
char zippo2[4][2];

zippo = (char(*)[2])malloc(sizeof(char[2]) * 4);


最佳答案

来自 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(*zippo)[2] = NULL;
char zippo2[4][2];

有不同的类型。第一个是指向 char[2] 类型的对象的指针。第二个是一个二维数组,包含四个 char[2] 类型的元素。

当数组 zippo2 在除引号中列出的表达式之外的表达式中使用时(例如将其与 sizeof 运算符一起使用),则其指示符将隐式转换为指向其第一个元素的指针,并具有与变量 zippo 类型相同。

关于c - 什么是c中的数组衰减以及它何时发生?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57268963/

相关文章:

c - 哈佛架构平台上的 NULL 指针问题

arrays - 无法将数组类型查询字符串解析为对象列表

java - 在排列的文本文件中搜索字符串

c - 难以理解使用链表实现图的方法

C++、字符串和指针

c - 使用 gcc 和 autoconf 链接程序时出现“找不到 -lc”错误

c++ - c/c++中用函数指针模仿OO,如何存储?

java - 分配Java类的二维数组

c++ - OpenGL 似乎没有读取我的顶点/索引

c - 数字到字符?