-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];

Community
  • 1
  • 1
Programmer
  • 199
  • 8
  • Are you looking for C-Style arrays? Remember, in modern C++, there is array class. – CroCo Jan 07 '17 at 06: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 Jan 07 '17 at 06:42
  • Specifically http://stackoverflow.com/a/16239446/11683 reads: "In C++11 it is possible". – GSerg Jan 07 '17 at 06: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 Jan 07 '17 at 06:47
  • I am not using c++ 11 or above. – Programmer Jan 07 '17 at 06:52
  • 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". – juanchopanza Jan 07 '17 at 08:15

1 Answers1

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];
R Sahu
  • 204,454
  • 14
  • 159
  • 270