如何传递的方法的二维阵列作为参数的高度和宽度? [英] How to pass a method the height and width of a 2d array as parameters?

查看:113
本文介绍了如何传递的方法的二维阵列作为参数的高度和宽度?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

说我有一个数组:数组[2] [4] ,主要方法里面,我有一个函数调用 blackandwhite 。我怎样才能通过这个方法,数组的长度和宽度作为参数?

Say I have an array: array[2][4], and inside the main method, I have a call to a function blackandwhite. How can I pass this method the length and width of the array as arguments?

推荐答案

这是一个可能的解决方案:

This is a possible solution :

void blackandwhite(int* array, int height, int width)
{
    // Array-processing done here.
    // array is pointer to int,
    // initially points to element myarray[0][0].
    // variable height = 2;
    // variable width = 4;

}


int main()
{
    int myarray[2][4];
    blackandwhite(&myarray[0][0], 2, 4);
}

人们可以发现一个阵列的大小,即在它的元素由下面的结构的数目:

One can find the size of an array i.e. the number of elements in it by the following construct :

int array[8];
int size = sizeof(array)/sizeof(array[0]);

不幸的是,C数组是本地数组,不包含在其中嵌入任何元数据。行和列只是重新presenting的方法/访问本质上是在内存中的线性存储空间。 AFAIK,没有办法来自动确定的行数/二维阵列的列,给定一个指向它的指针(在C)。

Unfortunately, C arrays are native arrays and do NOT contain any metadata embedded in them. Rows and Columns are just a way of representing/accessing what is essentially linear storage space in memory. AFAIK, there is no way to automatically determine the number of rows/columns of a 2D-array, given a pointer to it (in C).

因此​​,人们需要通过列/行作为独立参数的数量沿与指针二维数组如上面的例子中

Hence one needs to pass the number of columns/rows as separate arguments along-with the pointer to the 2D-array as shown in the example above.

这是一个相关的问题更多信息 <一个href=\"http://stackoverflow.com/questions/2411585/finding-dimensions-of-a-2d-array-in-c-using-pointers\">here.

More info on a related question here.

更新:

常见的陷阱一:在参数列表结果使用 INT **阵列
需要注意的是一个指针整数的2维阵列仍然是一个指针,指向中间体结果
INT ** 意味着参数指的是指针的指针为int,这是不是这里的情况。

Common pitfall no.1 : Using int** array in param-list
Note that a pointer to a 2 dimensional array of integers is still a pointer to a int.
int** implies that the param refers to a pointer to a pointer to an int, which is NOT the case here.

常见的陷阱之二:在参数列表 INT [] [] 结果
未能通过该阵列的尺寸(多个)。人们不必传递数组的第一个维度的大小(但你可能,但编译器会忽略它)。尾部的尺寸是强制性的,但。因此,

Common pitfall no.2 : Using int[][] in param-list
Failing to pass the dimension(s) of the array. One need NOT pass the size of the array's 1st dimension (but you may but the compiler will ignore it). The trailing dimensions are compulsory though. So,

// is INVALID!
void blackandwhite(int array[][], int height, int width)

// is VALID, 2 is ignored.
void blackandwhite(int array[2][4], int height, int width)

// is VALID.
void blackandwhite(int array[][4], int height, int width)

这篇关于如何传递的方法的二维阵列作为参数的高度和宽度?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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