Dynamic Value in array size

Hello,
I want to get row and column from the input.
How can I do it?


1
2
3
4
5
6
7
8
int main()
{


	int row;
	int column;
	int myarray[row][column];
}
Last edited on
You'll need to dynamically allocate memory for the array after you've received the user's input.

http://www.cplusplus.com/doc/tutorial/dynamic/
You have to allocate the memory dynamically.

C++ Standard Library has a container "vector" for that.
See: http://www.cplusplus.com/reference/vector/vector/
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
#include <vector>
#include <iostream>

int main()
{
  using RowType = std::vector<int>; // alias typename
  int row {2};
  int column {4};
  // you could read those from input here

  std::vector<RowType> myarray( row, RowType(column) );

  for ( auto& row : myarray ) {
    for ( auto elem : row ) {
      std::cout << elem << ' ';
    }
    std::cout << '\n';
  }
}


There are low level dynamic memory management options too and most courses go through them, but in practice you should learn and prefer the C++ Standard Library.
Topic archived. No new replies allowed.