我知道在 C 中不允许声明大小未知的二维数组。例如,如果我声明 array[][10] ,它将无法编译。我的问题是为什么当“数组”被声明为函数参数时它会编译。示例:
#define DIM 10
void func(int array[][DIM]){
//...someting
}
int main(int argc, char const *argv[])
{
int array[DIM][DIM];
func(array);
return 0;
}
最佳答案
来自n1570 (latest draft for C11) :
§6.7.6.3 函数声明符(包括原型(prototype)),p7:
A declaration of a parameter as ‘‘array of type’’ shall be adjusted to ‘‘qualified pointer to type’’, where the type qualifiers (if any) are those specified within the
[
and]
of the array type derivation. [...]
所以,如下:
void func(int array[][DIM]){
调整后实际上就是这样:
void func(int (*array)[DIM]){
这通常称为数组作为指针衰减。由于仅传递指针,因此编译器不需要知道整个数组的大小。但类型信息必须包括数组元素的大小(在本例中为第二维),以便索引和指针算术可以正常工作。
<小时/>另一方面,当您定义数组时,由于(希望如此)显而易见的原因,必须知道整个数组的大小:编译器必须为其保留存储空间。
关于C 为什么可以声明具有可变大小(但固定列)的二维数组的函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47078470/