0

I am not able to pass 2D array in C++ initialized by main function to addMatrix function.

ERROR MESSAGE
Main.cpp: In function 'int main()': Main.cpp:15:23: error: cannot convert 'int ()[(((sizetype)(((ssizetype)c) + -1)) + 1)]' to 'int' for argument '1' to 'void addMatrix(int, int*, int, int)'
addMatrix(a,b,r,c);

void addMatrix(int**, int**, int, int);

int main()
{   
  int r, c, i, j;
  cin >> r >> c;
  int a[r][c], b[r][c];
  // ASSUME HAVE TAKEN INPUTS FROM BOTH THE MATRIX A AND B
  addMatrix(a, b, r, c);
}

void addMatrix(int** a, int** b, int r, int c)
{ 
  int i, j, d[r][c];

  for(i = 0; i < r; i++)
     for(j = 0; j < c; j++)
        d[i][j] = a[i][j] + b[i][j];

  for(i = 0; i < r; i++)
  {
     for(j = 0; j < c; j++)
        cout << d[i][j] << " ";
     cout << endl;
  }
}
סטנלי גרונן
  • 2,740
  • 21
  • 43
  • 62
  • Note that Variable Length Arrays are not standard C++ and they are not covered in the answers there. Use proper multidimensional arrays (there are three ways given in the top answer, depending on how many sizes are known at compile time). – Yksisarvinen Apr 26 '20 at 14:31

1 Answers1

0

These declared arrays

int a[r][c],b[r][c];

used in expressions like for example function arguments are implicitly converted to pointers to their first elements of the type int ( * )[c].

However the corresponding function parameters have the type int **.

void addMatrix(int **,int **,int,int);

So the compiler issues an error because these types are not compatible.

Pay attention to that variable length arrays is not a standard C++ feature.

Use instead objects of the class template std::vector.

If your compiler supports variable length arrays then the function should be declared like

void addMatrix( int, int, int [][*], int [][*] );

Or if the declaration is at the same time the function definition then

void addMatrix( int r, int c, int [][c], int [][c] );

or (for self-documenting)

void addMatrix( int r, int c, int [r][c], int [r][c] );
Vlad from Moscow
  • 224,104
  • 15
  • 141
  • 268