-1

I learning multidimensional arrays in C++ and in the book there is the following example:

int (*b)[2] = new int[1][2];

Please explain why it is used this notation, instead of the standard

int b[1][2];

And in general, is there any difference between them? Thanks.

Alex
  • 13
  • 1
  • 5
  • 2
    heap and stack ... – donkopotamus Jan 15 '17 at 05:06
  • 1
    The first uses dynamic memory allocation, and will continue to exist until `b` is explicitly destroyed with operator `delete []`. The second, depending on where it is defined, is either of automatic storage duration (which means it ceases to exist when the containing scope completes) or static storage duration (which means it exists until the program exits). – Peter Jan 15 '17 at 05:09
  • 1
    Perhaps reading about `std::vector` and `std::array` would help – Ed Heal Jan 15 '17 at 05:41

2 Answers2

-1

int *b[2] is Array of 2 pointers

And

int (*b)[2] is pointers pointing to Array of size 2.

Priority of [] is higher than *.

int (*b)[2]

By this it means that rows are expandable( or they are dynamic) as it is pointer pointing to array of 2. while the column is statically allocated.

int b[1][2]

you are allocating memory statically which can't be dynamic.

Sachin Chauhan
  • 356
  • 1
  • 11
-2

First option:

int (*b)[2] = new int[1][2];
  • b is pointer to array[2] int and dynamically allocated to a 2D array in the heap. Refer to this to study about stack vs heap.
  • because b in this case is a pointer, it can be reassign to point to any other 2D array with the same size ie int [1][2] - whether that array is in stack of heap.

Second option:

int b[1][2];
  • b is a 2D array (although in memory it looks the same as 1D array as there is only a single row). As mentioned in the comments, b is stack/automatic variable.
  • Also b here is an array that means you cannot reassign it to point to anything else.
Community
  • 1
  • 1
artm
  • 17,291
  • 6
  • 38
  • 54