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

Christian picture Christian · Nov 28, 2011 · Viewed 23k times · Source

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?

Answer

Some programmer dude picture Some programmer dude · Nov 28, 2011

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.