传递一个二维数组到C ++函数 [英] Passing a 2D array to a C++ function
问题描述
我有我要带,作为一个参数,可变大小的二维数组的函数。
I have a function which I want to take, as a parameter, a 2D array of variable size.
到目前为止,我有这样的:
So far I have this:
void myFunction(double** myArray){
myArray[x][y] = 5;
etc...
}
和我在code声明数组别处:
And I have declared an array elsewhere in my code:
double anArray[10][10];
但是,调用 myFunction的(anArray)
给我一个错误。
我不希望当我通过它在阵列复制。在 myFunction的
所做的任何更改应该修改 anArray $状态C $ C>。如果我理解正确的话,我只是想在一个指针作为参数传递给一个二维数组。该功能需要接受不同大小也数组。因此,例如,
[10] [10]
和 [5] [5]
。我怎样才能做到这一点?
I do not want to copy the array when I pass it in. Any changes made in myFunction
should alter the state of anArray
. If I understand correctly, I only want to pass in as an argument a pointer to a 2D array. The function needs to accept arrays of different sizes also. So for example, [10][10]
and [5][5]
. How can I do this?
推荐答案
有三种方式来传递一个二维数组给一个函数:
There are three ways to pass a 2D array to a function:
-
该参数是一个二维数组
The parameter is a 2D array
int array[10][10];
void passFunc(int a[][10])
{
// ...
}
passFunc(array);
参数是包含指针数组
The parameter is an array containing pointers
int *array[10];
for(int i = 0; i < 10; i++)
array[i] = new int[10];
void passFunc(int *a[10]) //Array containing pointers
{
// ...
}
passFunc(array);
该参数是一个指针的指针
The parameter is a pointer to a pointer
int **array;
array = new int *[10];
for(int i = 0; i <10; i++)
array[i] = new int[10];
void passFunc(int **a)
{
// ...
}
passFunc(array);
这篇关于传递一个二维数组到C ++函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!