Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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

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

1 Answer

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...