假设我有一个数组:array[2][4]
,并且在 main 方法中,我调用了一个函数blackandwhite
。如何将数组的长度和宽度作为参数传递给该方法?
最佳答案
这是一个可能的解决方案:
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);
}
可以通过以下构造找到数组的大小,即其中元素的数量:
int array[8];
int size = sizeof(array)/sizeof(array[0]);
不幸的是,C 数组是 native 数组,不包含嵌入其中的任何元数据。行和列只是表示/访问内存中本质上线性存储空间的一种方式。 AFAIK,如果给定一个指向它的指针(在 C 中),则无法自动确定 2D 数组的行/列数。
因此,需要将列/行数作为单独的参数以及指向二维数组的指针传递,如上例所示。
有关相关问题的更多信息 here 。
<小时/>更新:
常见陷阱一:在 param-list 中使用 int** 数组
请注意,指向二维整数数组的指针仍然是指向 int 的指针。
int**
意味着参数引用一个指向 int 的指针,但这里的情况并非如此。
常见陷阱二:在 param-list 中使用 int[][]
无法传递数组的维度。不需要传递数组第一维的大小(但你可以,但编译器会忽略它)。不过,尾部尺寸是强制性的。所以,
// 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)
关于c - 如何将二维数组的高度和宽度作为参数传递给方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12881667/