我目前正在学习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/