Pointers on C——8 Arrays.18

来源:互联网 发布:mac系统最大化快捷键 编辑:程序博客网 时间:2024/05/27 20:50

​8.2.5 Multidimensional Arrays as Function Arguments

A multidimensional array name used as an argument to a function is passed the same as a one‐dimensional array name—a pointer to the first element of the array is passed.However, the difference between them is that each element of the multidimensional array is another array, and the compiler needs to know its dimensions in order to evaluate subscripts for the array parameter in the function. Here are two examples to illustrate the difference:

作为函数参数的多维数组名的传递方式和一维数组名相同——实际传递的是个指向数组第1 个元素的指针。但是,两者之间的区别在于,多维数组的每个元素本身是另外一个数组,编译器需要知道它的维数,以便为函数形参的下标表达式进行求值。这里有两个例子,说明了它们之间的区别:


int vector[10];

...

func1( vector );


The type of the argument vector is a pointer to an integer, so func1 can be prototyped in either of the following ways:

参数vector 的类型是指向整型的指针,所以func1 的原型可以是下面两种中的任何一种:


void func1( int *vec );

void func1( int vec[] );


Pointer arithmetic on vec in the function uses the size of an integer for its scale factor.

作用于vec 上面的指针运算把整型的长度作为它的调整因子。


Now letʹs look at a matrix.

现在让我们来观察一个矩阵:

int matrix[3][10];

...

func2( matrix );


Here the type of the argument matrix is a pointer to an array of ten integers. What should the prototype for func2 look like? Either of the following forms could be used:

这里,参数matrix的类型是指向包含10 个整型元素的数组的指针。func2 的原型应该是怎样的呢?你可以使用下面两种形式中的任何一种:


void func2( int (*mat)[10] );

void func2( int mat[][10] );


In the function, the first subscript used with mat is scaled by the size of an array of ten integers; the second subscript is then scaled by the size of an integer, just as it would be for the original matrix.

在这个函数中, matrix的第1 个下标根据包含10 个元素的整型数组的长度进行调整,接着第2 个下标根据整型的长度进行调整,这和原先的matrix 数组一样。


The key here is that the compiler must know the sizes of the second and subsequent dimensions in order to evaluate subscripts, thus the prototype must declare these dimensions. The size of the first dimension isnʹt needed because it is not used in the calculation of subscripts.

这里的关键在于编译器必须知道第2 个及以后各维的长度才能对各下标进行求值,因此在原型中必须声明这些维的长度。第1 维的长度并不需要,因为在计算下标值时用不到它。


You can write the prototype for a one‐dimensional array parameter either as an array or as a pointer. For multidimensional arrays, you only have this choice for the first dimension, though. Specifically, it is incorrect to prototype func2 like this:

在编写一维数组形参的函数原型时,你既可以把它写成数组的形式,也可以把它写成指针的形式。但是,对于多维数组,只有第1 维可以进行如此选择。尤其是,把func2 写成下面这样的原型是不正确的:


void func2( int **mat );


This example declares mat to be a pointer to a pointer to an integer, which is not at all the same thing as a pointer to an array of ten integers.

这个例子把mat 声明为一个指向整型指针的指针,它和指向整型数组的指针并不是一回事。


上一章 Pointers on C——8 Arrays.17

原创粉丝点击