C 为什么可以声明具有可变大小(但固定列)的二维数组的函数

标签 c arrays multidimensional-array

我知道在 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/

相关文章:

python - 在 Python 3 中向数组添加坐标

c - C 中的符号 (((nodeptr) (bodyptr)) -> type) 是什么意思?

arrays - 从数组中获取对象

python - 在 C/Java 中处理正则表达式的速度比在 Python 中快多少?

ios - 将自定义对象的 NSArray 转换为 Swift 数组

C++ 多维数组成员访问器

javascript - 多维javascript

PHP 给定递增的数字,计算所有可能的组合

c - 如何将 64 字节字符串转换为 20 字节字符串?

c - 如何在一个循环中对C中的数组进行排序?