0
#include <iostream>

using namespace std;

void input(int row, int col, int *m) {    
    for (int i = 0; i < row; i++) {
        cout << "Enter the element of row " << i + 1 << ": \n";
        for (int j = 0; j < col; j++) {
            cout << "Element " << j + 1 << ": ";
            cin >> m[i][j];
            cout << "\n";
        }
    }

    for (int i = 0; i < row; i++) {
        cout << "\n";
        for (int j = 0; j < col; j++)
            cout << m[i][j] << "\t";
    } 
}

int main() {
    int row, col;
    cout << "Enter row of the matrix: ";
    cin >> row;
    cout << "\nEnter col of the matrix: ";
    cin >> col;
    int matrix[row][col];
    input(row, col, (int*)matrix);    
}

When I compile this program, I kept receiving an error such as "

cannot convert 'int (*)[col]' to 'int*' for argument '3' to 'void input(int, int, int*)'
     input(row, col, matrix);
John Kugelman
  • 349,597
  • 67
  • 533
  • 578
Zoey
  • 1
  • 1
  • `void input(int row, int col, int *m)` is almost a valid C trick for passing a 2D array of runtime-determined size. There is no such trick in C++. – user4581301 Jun 04 '22 at 15:53
  • `int *m` is a pointer to one or more `int`s. `matrix` will decay to a pointer to one or more arrays of `col` `int`s, not to an `int*` or an int **. You brute-force it with the cast in `(int*)matrix`, but that's not a 100% good idea. – user4581301 Jun 04 '22 at 15:57
  • `int *m` can be accessed with `m[index]`. You can't get two dimensions out of it like you try with `m[i][j]`. – user4581301 Jun 04 '22 at 15:58
  • 1
    All this you can't you can't you can't. Sucks huh? You got into this mess because of `int matrix[row][col];` In Standard C++, you can't do that either, so the language doesn't support passing `matrix` around. There is no need for syntax to do it since you aren't supposed to do it at all. – user4581301 Jun 04 '22 at 16:00
  • 1
    But enough negativity. You can make a 1D structure of dynamic size and pretend it's 2D. The easiest way to do this is make a wrapper class [like Doug does here](https://stackoverflow.com/a/36123944/4581301) and pass instances of the wrapper – user4581301 Jun 04 '22 at 16:02

0 Answers0