为什么C / C ++允许在函数调用多维数组的最左边指数的遗漏? [英] why c/c++ allows omission of leftmost index of a multidimensional array in a function call?

查看:117
本文介绍了为什么C / C ++允许在函数调用多维数组的最左边指数的遗漏?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我只是想知道,为什么允许它省略多维数组的最左边指数传递数组给一个函数是什么时候?为什么不超过一个指标?和编译器如何找出一个指标省略大小?

I was just wondering why it is allowed to omit the leftmost index of a multidimensional array when passing the array to a function ? Why not more than one indexes? And how does the compiler find out the size with one index omitted ?

推荐答案

其他答案中描述的C标准如何处理数组指针转换以及如何影响函数声明,但我觉得他们没有进入的为什么的,所以在这里我去...

Other answers described how the C standard handles array to pointer conversion and how this affects the function declaration, but I feel they didn't go into the why, so here I go...

在C,阵列放置在内存中排列紧密的元素。

In C, arrays stand for tightly packed elements in memory.

A -> _ _ _ _ _ _ ...
i:   0 1 2 3 4 5 ...

在上面的例子中,每个数组元素是1 _ 宽。找到的第i个元素,我们因此必须到第i个地址。 (请注意,最左边的尺寸(大小)在这里并不重要)

In the above example, each of the array elements is 1 _ wide. To find the i-th element, we thus have to go to the i-th address. (Note that the leftmost dimension (the size) doesn't matter here)

现在考虑一个多维数组:

Now consider a multidimensional array:

B -> [_ _ _][_ _ _][_ _ _][_ _ _]...
i:    0 0 0  1 1 1  2 2 2  3 3 3
j:    0 1 2  0 1 2  0 1 2  0 1 2
     ^first row    ^third row

要找到偏移的[I] [J] 我们需要跳过我行(3 * I),然后通过Ĵ元素 - >(3 * I + J)。注意,如何也没有此处所需要的第一尺寸的大小。

To find the offset of A[i][j] we need to jump over i rows (3*i) and then over j elements -> (3*i + j). Note how the size of the first dimension is also not needed here.

应该使用数组的它只是在创建它需要的时候很清楚现在的话,那是不是需要最左边的大小

由于没有的需求的给予最左边指数的尺寸,那么为什么不给它无论如何,为了完整的缘故?毕竟,这是在Pascal编程语言(一个C当代)来完成。

Since there is no need to give the dimension of the leftmost index, then why not give it anyway, for completeness sake? After all, this is what is done in the Pascal programming language (a C contemporary).

好吧,这对数组操作大部分功能适用于所有可能数组的长度相同,因此指定大小只会伤害你重用它们的能力。

Well, most functions that operate on arrays work the same for all possible array lengths, so specifying the size would only hurt your ability to reuse them.

例如,为什么

int sum(int arr[10]){
    int s = 0, i;
    for(i=0; i<10; i++){
        s += arr[i];
    }
    return s;
}

当你可以做到这一点,而不是:

When you can do this instead:

int sum(int arr[], int n){
    int s = 0, i;
    for(i=0; i<n; i++){
        s += arr[i];
    }
    return s;
}


至于省略一个以上的尺寸,这一点使用一般的多维数组时(因为你需要知道的尺寸,知道什么时候第一行结束,第二次首发)是不可能的。不过,如果你愿意花的暂存空间一些(小)额外的内存,这是完全可以用指针来代替的指针:<一href=\"http://www.eskimo.com/~scs/cclass/int/sx9b.html\">http://www.eskimo.com/~scs/cclass/int/sx9b.html

这篇关于为什么C / C ++允许在函数调用多维数组的最左边指数的遗漏?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆