简体   繁体   中英

A small question about structure of dynamic multidimensional array in C++

What exacly this repetition of [4] does in this declaration of dynamic multidimensional array?

int (*array)[4] = new int[10][4];

If you have an array like this

T a[10];

then T is the type of elements of the array.

To dynamically allocate such an array you have to write

T *array = new T[10];

Let's now define T as a typedef name the following way

typedef int T[4];

or

using T = int[4];

So this declaration

T *array = new T[10];

is valid also and for this typedef.

Now let's substitute T for its typedef definition in the reversed way. We will get

int ( *array )[4] = int[10][4];

So the operator new allocates a two dimensional array with 10 "rows" each of which is in turn an array of 4 integer elements.

This record

int ( *array )[4] 

means pointer to an array (element of the two-dimensional array) of 4 elements.

To make it more clear let's you have an array like

T a[N1][N2];

This declaration of a two-dimensional array you may rewrite like

T ( a[N1] )[N2];

The both declarations declare the same two-dimensional array.

To get pointer to the type of element of the array just substitute the record ( a[N1] ) for ( *p ) . For example

T ( a[N1] )[N2];
T ( *p ){N2] = a;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM