Search code examples
c++arraysmultidimensional-arraydynamic-sizing

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?


Solution

  • 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.