-1

I want to create a variable sized two dimensional array with number of rows as m and number of columns as n. th value of m and n is taken from the user during execution time. the following method works and produce output. Now let me know whether this is technically ok in all scenarios related to cpp.

#include<iostream>
using namespace std;

int main() {
    int **arr, m,n;
    cout<<"enter";
    cin>>m>>n;
    arr = new int*[m];

    for(int i = 0; i < m; i++) {
        arr[i]=new int[n];  // initializing a variable-sized array
    }

    for(int i = 0; i < m; i++) {
        for(int j = 0; j < n; j++) {
            cout<<arr[i][j];  // printing the array
        }
    }
}
marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459

1 Answers1

-2

From what you are saying I think you want a 2dimensional array where the number of columns and rows are determined on runtime.

so to create this array we use this syntax:

int l = 5; //set this on runtime with a cin or something else
int k = 5; //set this on runtime with a cin or something else

int array [k][l] = {};

congrats this piece of code creates a multidimensional array of a 5x5 size where each integer is initialized with the number '0' since this is the default initialization for an integer

For more information you should check these links:

Declaring and initializing arrays

Multidimensional arrays

Jelle Bleeker
  • 131
  • 11
  • Thanks for the response. But in this program the value of l and k will be set during run time. Its before the 2D array is initialized. Is't that enough?? – Harry Krish Jul 25 '19 at 14:53
  • in this example, I set the values for l and k to 5. In any program, you can set those values to any integer you like in whatever way you like. whether that is by accepting user input or by picking random numbers. The array you initialize will be initialized with whatever values l and k have at that very moment. as long as you set l and k before initializing and don't want to resize your array afterward then this should be what you want. – Jelle Bleeker Jul 25 '19 at 19:52