Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Proper way to declare a variable length two dimensional array in C++

I would like to get a two dimensional int array arr that I can access via 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 is however variable and as far as I understand this syntax doesn't work if the size of the array isn't hardcoded but I use a variable like int arr[sizeX][sizeY].

What's the best workaround?

like image 241
Christian Avatar asked Dec 17 '22 06:12

Christian


1 Answers

If you don't want to use a std::vector of vectors (or the new C++11 std::array) then you have to allocate all sub-arrays manually:

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

And of course don't forget to delete[] all when done.

like image 95
Some programmer dude Avatar answered Dec 31 '22 00:12

Some programmer dude