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

what is array decay in c and when it happen?

我目前正在学习C语言。 我想知道 'array decaying' 是什么意思,什么时候发生。

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


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.

类型相同