Search code examples
c++arraysnew-operator

Easy way to create multiple-dimension arrays in C++ with new operator


I need to create a lot of small 2-dimension arrays in C++ code. The problem is that it's a lot of work to create even a simple array:

new int* [2]{
            new int[2]{9, 9},
            new int[2]{25, 19}
    };

Is there any better way how to do that? I wanted to avoid writing "new int[]..." every time.


Solution

  • If the dimensions are not decided at runtime, and all the inner arrays have the same dimensions, you do not need dynamic allocation here.

    Just declare an array:

    int myArray[2][2] = {
       {9, 9},
       {25, 19}
    };
    

    That's it!