The correct way to declare a two-dimensional array of variable length in C ++

I would like to get a two-dimensional array of int arr , with which I can access through arr [i] [j].

As far as I understand, I could declare int arr[10][15]; to get such an array. In my case, the size, however, is variable, and as far as I understand, this syntax does not work if the size of the array is not hardcoded, but I use a variable like int arr[sizeX][sizeY] .

What is the best workaround?

+4
source share
6 answers

If you do not want to use std::vector vectors (or the new C ++ 11 std::array ), then you need to select all subarrays manually:

 int **arr = new int* [sizeX]; for (int i = 0; i < sizeX; i++) arr[i] = new int[sizeY]; 

And of course, don't forget delete[] everything when this is done.

+11
source

c / C ++ does not support a multidimensional array. But it supports array array:

  //simulate 2-dimension array with 1-dimension array { int x = 20; int y = 40; int * ar = new int(x*y); int idx_x =9; int idx_y=12; ar[idx_x + idx_y * x] = 23; } //simulate 2-dimension array with array of array { int x = 20; int y = 40; int**ar = new int*[y]; for(int i = 0; i< y; ++i) { ar[i] = new int[x]; } ar[9][12] = 0; } 
+1
source

If you are looking for a solution in C, see this thread: How to work with dynamic multidimensional arrays in C? .

If C ++ is fine, then you can create a 2D vector, i.e. vector vectors. See http://www.cplusplus.com/forum/general/833/ .

0
source

You cannot, with array syntax. The language requires that you use compile-time constants to create arrays.

0
source

C ++ does not have variable length arrays. You can use vector<vector<int> > . It can also be accessed using arr[i][j] .

0
source

Like fefe said, you can use vector vectors, e. g.

 #include<iostream> #include<vector> using namespace std; int main() { vector< vector<int> > vec; vector<int> row1; row1.push_back(1); row1.push_back(2); vector<int> row2; row2.push_back(3); row2.push_back(4); vec.push_back(row1); vec.push_back(row2); for( int ix = 0; ix < 2; ++ix) for( int jx = 0; jx < 2; ++jx) cout << "[" << ix << ", " << jx << "] = " << vec[ix][jx] << endl; } 
0
source

Source: https://habr.com/ru/post/1383398/


All Articles