If you have an array declaration of the form
T a[N];
where T is some type and N is the number of elements in the array, then the pointer to the first element of the array will be of type T * . for example
T *p = a;
After this definition, the pointer p points to the first element of the array a .
To allocate memory dynamically for an array similar to the array defined above, you can write
T *p = new T[N];
Here, the array element is of type T , and p as above, shows the first element of the dynamically allocated nameless array.
Now imagine that T is an alias for the type of short[20] , for example
typedef short T[20];
Then previously displayed ads for the pointer can be written as
T *p = &a;
and
T *p = new T[1];
If we again return to the original type of short[20] , we get
short( *p )[20] = &a;
and
short( *p )[20] = new short[1][20];
The last sentence means that an array is selected from one element (you can select an array from an arbitrary number of elements in accordance with your task), whose elements in turn are arrays of 20 short elements.
Keep in mind that when so-called pointer arithmetic is used, the pointer value changes to a multiple of sizeof( T )
So if, for example, you declare a pointer as
short( *p )[20] = &a;
where T equivalent to short[20] , then after applying, for example, an increment to this pointer
++p;
the pointer will contain the address immediately after the last element of the array a .
Well, and finally, an example of working with such a pointer.
#include <iostream> #include <iomanip> #include <algorithm> #include <numeric> #include <iterator> const size_t N = 20; short ( * create_2D_array( size_t n ) )[N] { short ( *p )[N] = new short[n][N]; return p; } int main() { short a[N]; std::iota( std::begin( a ), std::end( a ), 1 ); for ( short x : a ) std::cout << std::setw( 2 ) << x << ' '; std::cout << std::endl; short ( *p )[N] = create_2D_array( 1 ); std::iota( std::reverse_iterator<short *>( *p + N ), std::reverse_iterator<short *>( *p ), 1 ); for ( short x : *p ) std::cout << std::setw( 2 ) << x << ' '; std::cout << std::endl; std::cout << std::endl; std::swap( a, *p ); for ( short x : a ) std::cout << std::setw( 2 ) << x << ' '; std::cout << std::endl; for ( short x : *p ) std::cout << std::setw( 2 ) << x << ' '; std::cout << std::endl; delete [] p; return 0; }
Output of the program to the console
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 20 19 18 17 16 15 14 13 12 11 10 9 8 7 6 5 4 3 2 1 20 19 18 17 16 15 14 13 12 11 10 9 8 7 6 5 4 3 2 1 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20