传递multidimesional阵列中的C / C ++

问题描述:

为什么C / C ++它是需要一个接收MD ARR到了所有子阵列的尺寸一个FUNC参数/尺寸?

Why in C/C++ it is needed for a func param that receives a MD arr to has the sizes of all sub arrays/dimensions?

这里(PDF):它说MD ARRS的唯一区别是,
编译器会记住每一个虚数维但是当我违反了这些方面的编译器不执行任何操作,例如:

here(PDF): It says the only difference of MD arrs is that "the compiler remembers each imaginary dimension" but when I violate these dimensions compiler does nothing, e.g.:

char arr[3][5];
arr[0][5] = 10;

那么,什么是缅怀那些大小的点?

So, what's the point of remembering those sizes?

索引访问到一个数组中必须计算的内存基于索引值的的声明逊色尺寸抵消行优先顺序排列的计算。更详细的介绍一下。

Indexed access into an array must compute memory offset calculations in row-major order based on the index value and declared inferior dimensions. More on that in a bit.

但首先,你的问题是密切相关的这个简单的观察:

But first, your question is tightly related to this simple observation:

void foo( char a[] )
{
    a[5] = 'a';
}

// caller of foo() from somewhere
char arr[5];
foo(arr);

为什么编译器让你做的的??因为这是C,而你完美您的权利内的未定义行为要拍你自己的脚了。牢记这一点:

Why does the compiler let you do that ?? Because this is C, and you're perfectly within your rights to shoot your own foot off with undefined behavior. Keeping this in mind:

void foo( char a[][5] )
{
    a[0][5] = 'a';
}

// caller of foo() from somewhere
char arr[4][5];
foo(arr);

这就像有效作为前code(即您在您自己的风险和危险,进入UB右内准备得很好)。在这种情况下,将工作,但只是因为对底层数组进行线性背景是与20个元件宽,我们只访问第六元素,这在技术上是改编[1] [0]

这些劣质尺寸的目的是要正确计算如访问的这个的:

The purpose of those inferior dimensions is to properly calculate access like this:

void foo( char a[][5] )
{
    a[2][1] = 'b';
}

2 卓越的指数必须使用申报劣质尺寸(在这种情况下, 5 ),以有效地计算出的线性偏移正确的元素。铺设在一维线性块中的二维数组,用它来做到这一点:

The 2 superior index must use the declared inferior dimension (in this case 5) to effectively calculate the the linear offset of the proper element. Laying out the 2D array in a 1D linear block, it is used to do this:

char arr[20]; // 4*5
arr[2*5+1] = 'b';

请注意在 5 。它的劣势宣告尺寸,必须知道正确计算行的飞跃(比喻)。

Note the 5. It, the declared inferior dimension, must be known to properly calculate the row-leap (figure of speech).

我希望这使得它至少更清楚一点。

I hope that makes it at least a little clearer.

我要指出,这种化合物。即,以下内容:

I should note that this compounds. I.e., the following:

char arr[3][4][5];
arr[1][2][3] = 'c';

有效地计算对底层数组进行线性背景下的正确位置:

effectively computes the correct location against the linear backdrop of the underlying array:

char arr[60]; // 3*4*5
arr[ 1*(4*5) + 2*(5) + 3 ] = 'c';

等。采取了尽可能多维度作为你的愿望。所有的劣质尺寸必须知道正确做到这一点。

And so on. Take that out to as many dimensions as you desire. All the inferior dimensions must be known to do this properly.