按值传递二维数组不起作用 [英] Passing 2D array by value doesn't work
本文介绍了按值传递二维数组不起作用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想传递一个二维数组到一个函数。我不希望实际数组修改。所以,按值传递。但我的实际2darray是越来越修改。(当我修改myArray的,X是越来越修改)。为什么会这样呢?
I am trying to pass a 2d array to a function. I don't want the actual array to be modified. So pass it by value. But my actual 2darray is getting modified.(when i modify myArray, x is getting modified). Why is it so?
int main(int argc, const char* argv[])
{
int x[3][3];
x[0][0]=2;
x[0][1]=2;
x[0][2]=2;
x[1][0]=2;
x[1][1]=2;
x[1][2]=2;
x[2][0]=2;
x[2][1]=2;
x[2][2]=2;
func1(x);
}
void func1(int myArray[][3])
{
int i, j;
int ROWS=3;
int COLS=3;
for (i=0; i<ROWS; i++)
{
for (j=0; j<COLS; j++)
{
myArray[i][j] =3;
}
}
}
和有可能按值传递一个二维数组,如果我们不知道这两个方面?
And is it possible to pass a 2D array by value if we don't know both dimensions?.
推荐答案
要prevent func1的,将其更改为一个const指针。
to prevent func1 from being changed, change it to a const pointer.
void func1(const int (*myArray)[3])
{
int i, j;
int ROWS=3;
int COLS=3;
for (i=0; i<ROWS; i++)
{
for (j=0; j<COLS; j++)
{
// myArray[i][j] =3; //compilation error, is now const
cout <<" "<<myArray[i][j];
}
}
}
这篇关于按值传递二维数组不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文