Skip to main content

You are not logged in. Your edit will be placed in a queue until it is peer reviewed.

We welcome edits that make the post easier to understand and more valuable for readers. Because community members review edits, please try to make the post substantially better than how you found it, for example, by fixing grammar or adding additional resources and hyperlinks.

25
  • 173
    Remember that anything allocated with new is created on the heap and must be de-allocated with delete, just keep this in mind and be sure to delete this memory from the heap when you're done with it to prevent leaks.
    – Kekoa
    Commented Jun 1, 2009 at 20:51
  • 98
    Also note that this one is an array of pointers. not of arrays. The pointer in turn point to arrays. Important to really correct on the terms, since many tutorials get it wrong too. An array of arrays would be contiguous, which this one is not Commented Jun 1, 2009 at 20:53
  • 5
    Yes, a T[][N] would be called "array of array [N] of T" and be an incomplete type, while T[][] would be an invalid type (all except the last dimensions must have a known size). T[N][M] is "array [N] of array[M] of T", while yours, T[sizeX] is "array [sizeX] of T" where T is a pointer to an int. Creating a dynamically 2d array works like this: new int[X][Y]. It will create an array of an allocated-type int[X][Y]. This is a "hole" in C++'s type system, since the ordinary type system of C++ doesn't have array dimensions with sizes not known at compile time, thus these are called "allocated types" Commented Jun 1, 2009 at 21:00
  • 46
    Oh my God, this is complete garbage, this is utterly wrong. This is no 2D array. "A dynamic 2D array is basically an array of pointers to arrays." – NOOOO, FFS! T (*ptr)[M] = new T[N][M]; is the correct solution… No amount of arrays-of-pointers will ever be the same as an array-of-arrays… Commented Jun 9, 2016 at 20:34
  • 8
    @TheParamagneticCroissant You can argue it is not a 2D array. It's true. It can be indexed like a 2D array, but it is not a 2D array. The memory layout is in fact portrayed in the picture. The problem with that statement is it fails to work if M is not constant. Commented Jun 9, 2016 at 23:51