C ++数组作为参数-为什么只需要指定"outer"方面 [英] C++ array as parameter - why do you only need to specify "outer" dimension

查看:110
本文介绍了C ++数组作为参数-为什么只需要指定"outer"方面的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试找出多维数组,尤其是如何通过将它们传递给函数来填充它们.这都是非常不直观的,但是所有最不直观的事情对我来说毫无意义:

I'm trying to figure out multidimensional arrays and specifically how to fill them by passing them to functions. It's all very unintuitive, but the unintuitivest thing of all, which doesn't make any sense at all to me is:

为什么将2d数组作为参数传递时,必须指定列数,而不是行数?我可能看过五个或更多提供该语法的论坛线程,但没有一个线程解释其背后的原因.我对编译器需要知道要在其上进行操作的数组的大小表示满意,但是二维数组基本上不是数组的数组吗?

Why do you have to specify the number of columns, but not the number of rows when passing an 2d array as a parameter? I've probably looked at five or more forum threads that give the syntax, but none of them explained the reasoning behind it. I am okay with the compiler needing to know the size of an array to operate on it, but isn't a bidimensional array basically an array of arrays?

推荐答案

但是二维数组基本上不是数组吗?

but isn't a bidimensional array basically an array of arrays?

是的.

但是编译器实际上需要知道大小,以便能够在对数组建立索引时正确地执行指针算术(当然,除了分配以外,我们在这里是在函数上下文中进行讨论的),因为多维数组在内存中是连续的. int arr[2][3]声明一行中有3个int,并且两行3 int行紧随其后.

But the compiler needs to know the size really just in order to be able to perform pointer arithmetic correctly when indexing into the array (well, apart from allocation of course, but we are speaking in the context of functions here), since multidimensional arrays are continuous in memory. int arr[2][3] declares that there be 3 ints in a row, and two pieces of 3-int rows follow each other.

现在,当您将数组传递给函数时,数组将发生变化,因为它们会衰减为指针.但是,第一(最内)维衰减为一是合乎逻辑的,因为我们可以使用单个指向其第一元素的指针(理论上)对任意长的数组进行索引.

Now what happens to arrays when you pass them to a function is that they decay into a pointer. But it's only logical that the first (innermost) dimension decays into one, because we can index (in theory) an arbitrarily long array using a a single pointer to its first element.

但是,如果有多个维度,则编译器需要这些维度,以便编译器可以在其他维度上执行指针算术.

If, however, there are multiple dimensions, then the compiler needs those dimensions so that it can perform pointer arithmetic on further dimensions.

这是您还应该阅读的内容.

Here is something you should read in addition.

这篇关于C ++数组作为参数-为什么只需要指定"outer"方面的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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