If you want to access particular element or operate on the array but if you want to create the matrix dynamically, you can use use pointers to access each element by passing the dimensions in the print function.
Since if you have a multidimensional array defined as int [][], then
x = y[a][b] is equivalent to x = *((int *)y + a * NUMBER_OF_COLUMNS + b);
Check this post for more details: How to use pointer expressions to access elements of a two-dimensional array in C?
So, if you want to print whole matrix or access any particular element, you can do like:
#include <iostream>
using namespace std;
//the function print_2D_matrix receives 4 arguments: pointer to first element
// dimension of array arr, i.e. n x m
// index of the element to be printed, i.e. a and b
void print_2D_matrix(int *arr, int n, int m, int a, int b){
for(int i = 0; i < n; i++){
for(int j = 0; j < m; j++)
printf("%d ", *(arr + (i * m) + j));
printf("\n");
}
//go to the address just before a row, i.e. (a - 1) * NO_OF_COLUMNS
//then go to the address on b column, i.e. (a - 1) * NO_OF_COLUMNS + b
//since we started from the base address, i.e. first element( arr[0][0] ), subtract 1
printf("arr[3][3] = %d\n", *(arr + ((a - 1) * m) + b - 1)); //print arr[a][b]
}
int main() {
int n, m;
cin>>n>>m;
int arr[n][m];
for(int i = 0; i < n; i++) //initialize the matrix
for(int j = 0; j < m; j++)
arr[i][j] = i * j;
print_2D_matrix((int *) arr, n, m, 3, 3);
return 0;
}
Output for above program (for n x m = 4 x 5) is:
0 0 0 0 0
0 1 2 3 4
0 2 4 6 8
0 3 6 9 12
arr[3][3] = 4