-2

I have already seen :

How do I declare a 2d array in C++ using new?

But none of the answer seems to answer the question "How to declare a ** 2D array using new ** ?"

All the answers seems to show alternatives either by declaring array of pointers or by declaring row*column sized single dimensional array and then using row, column calculations explicitly.

But is there any way to directly allocate a 2D array in the heap in c++ just in the same way we do in the stack?

Example :

int stackarray[3][2];

//Is there some equivalent to above?? Like :

= new int[3][2];

6
  • Are you looking for C-Style arrays? Remember, in modern C++, there is array class.
    – CroCo
    Commented Jan 7, 2017 at 6:41
  • 1
    The second answer to the question you linked answers this question. It's important to actually read the answers, not just selectively look at one and decide it's not the one you want.
    – Ken White
    Commented Jan 7, 2017 at 6:42
  • Specifically stackoverflow.com/a/16239446/11683 reads: "In C++11 it is possible".
    – GSerg
    Commented Jan 7, 2017 at 6:44
  • @Ken White ; You should first actually read my question before suggesting answers. What I said in my question is that : "Answers have shown alternatives using arrays of pointers or row*column sized single dimensional array. But none of them has answered whether new int [rows][columns] is possible or not"
    – Programmer
    Commented Jan 7, 2017 at 6:47
  • 2
    The duplicate you linked has pretty much the same answer as the one posted here (except for some reason it makes it seem it only applies to C++11.) But you should specify if you need both dimensions to be set at runtime. In which case, the answer is "no". Commented Jan 7, 2017 at 8:15

1 Answer 1

3

But is there any way to directly allocate a 2D array in the heap in c++ just in the same way we do in the stack?

Yes.

Method 1 (C++11 or higher)

auto arr = new int[3][2];

Method 2

int (*arr)[2] = new int[3][2];

arr is a pointer to int [2], i.e. an array of 2 ints. With that allocation, the valid indices to access the elements of the 2D array are arr[0][0] -- arr[2][1]

Method 3

typedef int ARRAY1[2];
ARRAY1* arr = new ARRAY1[3];

or if using C++11 or higher,

using ARRAY1 = int[2];
ARRAY1* arr = new ARRAY1[3];
2
  • Please can you give explanation of method 2?
    – Programmer
    Commented Jan 7, 2017 at 6:49
  • Give explanation please
    – Programmer
    Commented Jan 10, 2017 at 19:38

Not the answer you're looking for? Browse other questions tagged or ask your own question.