1

https://stackoverflow.com/a/936702/462608

A dynamic 2D array is basically an array of pointers to arrays.

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

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

new int*[rowCount];.

  • What does star indicate there?

  • Is a 2D array an array of pointers to array?

Community
  • 1
  • 1
Aquarius_Girl
  • 21,790
  • 65
  • 230
  • 411

3 Answers3

7
  1. The star is part of the type of what is being allocated. new int*[rowCount]; allocates a dynamic array of rowCount pointers-to-int, and returns a pointer to the first one.

  2. No. A 2D array is an array, whose elements are 1D arrays, i.e. T[M][N], as opposed to an array of pointers, whose elements are... well, pointers.
    The difference is easy to spot: a 2D array is backed by a single, contiguous chunk of memory, while an array of pointer (that themseves point to arrays) has its memory scattered around in no particular order.

Quentin
  • 62,093
  • 7
  • 131
  • 191
4

In this expression

new int*[rowCount];.

there is allocated an array with rowCount elements of type int *. That is each element of the array is a scalar object.

A multidimensional (or two-dimensional) array is an array elements of which are in turn arrays.

Thus to allocate a two-dimensional array you should write

new int[rowCount][colCount];

Or you could write

typedef int TElement[colCount];

new TElement[rowCount]; .

The problem with this allocation is that the variable colCount must be a compile-time constant. If the value of the variable is not known at compile-time you may not use such an allocation.

So in this case usually an array of pointers is allocated as it is shown in your question

int **a = new int*[rowCount];.

and then each element of the one-dimensional array is initialized by the address of a newly allocated one dimensional array like

for ( size_t i = 0; i < rowCount; i++ )
{
    a[i] = new int[colCount];
}
Vlad from Moscow
  • 301,070
  • 26
  • 186
  • 335
1

What does star indicate there?

The syntax here is new type [size]. In new int*[rowCount], int* is the type, i.e. int pointer.

Is a 2D array an array of pointers to arrays?

It's different in dynamic and static multidimensional arrays. In static arrays, memory is allocated as 1D array (linear) and accessed as a 2D array.

A 2D dynamic array is an array of pointers to type, which, in your case, is int. Each element points to the first element of type, if initialized. In simpler words, it is an array of addresses to first elements of type. While accessing, it just adds sizeof(type) to that address to access the required index.

codedrunk
  • 43
  • 7