Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
293 views
in Technique[技术] by (71.8m points)

c++ - Passing 2D array by value doesn't work

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?.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You can take advantage of the fact that arrays in user defined types are copied and assigned when instances of that type are copied or assigned, for example

template <size_t N, size_t M>
struct Foo
{
  int data[N][M];
};

template <size_t N, size_t M>
void func1(Foo<N, M> foo)
{
  foo.data[1][2] = 42;
}

int main()
{
  Foo<3, 3> f;
  f.data[0][0]=2;
  ...
  func1(f);
}

Here, func1 has a local copy of the foo, which has its own copy of the array. I have used templates to generalize to arbitrary sizes.

Note that C++ provides the std::array template, which you could use instead of Foo, so in real code you would do something like this:

#include <array>

template <typename T, size_t N, size_t M>
void func1(std::array<std::array<T, N>, M> arr)
{
  arr[1][2] = 42;
}

int main()
{
  std::array<std::array<int, 3>, 3> a;
  a[0][0]=2;
  ...
  func1(a);
}

If you are stuck with pre-C++11 implementations, you can use either std::tr1::array (header <tr1/array> or boost::array from the boost library. It is also a nice exercise to roll out your own.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

56.9k users

...