Search code examples
c++carraysfunction-callsfunction-call

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


Solution

  • 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];  
             }
         }
    }