-5

In c++

char (*test)[10];

test = new char[4][10];

what the meaning of above two declarations?

Vlad from Moscow
  • 301,070
  • 26
  • 186
  • 335
AKP
  • 1
  • Related: https://stackoverflow.com/q/13910749/12416453 – Ch3steR Sep 26 '21 at 18:34
  • Does this answer your question? [Difference between \*ptr\[10\] and (\*ptr)\[10\]](https://stackoverflow.com/questions/13910749/difference-between-ptr10-and-ptr10) – st.huber Sep 27 '21 at 10:24

2 Answers2

1
char (*test)[10];

The first line declares test to be a pointer to char[10].

test = new char[4][10];

The second line creates a char[4][10], an array with 4 elements of type char[10], and assigns the pointer to the first element of this array to test.

It is similar to

 T* test;          // pointer to T
 test = new T[4];  // create array with 4 elements 
                   // and assign pointer to first element to test
463035818_is_not_an_ai
  • 109,796
  • 11
  • 89
  • 185
0

When you have an array then used in expressions (with rare exceptions) it is converted to a pointer to its first element.

So for example if you have the following array declaration

char arr[4][10];

then it is converted in an expression as for example used as an initializer expression to pointer to its first element of the type char ( * )[10].

So you may write for example

char (*test)[10] = arr;

The operator new that allocates memory for an array also returns a pointer to the first element of the allocated array. So if you want to allocate an array of the type char[4][10] then you can write

char (*test)[10] = new char[4][10];

Here char[10] is the type of elements of the allocated array. So a pointer to an element of the array has the type char ( * )[10].

Vlad from Moscow
  • 301,070
  • 26
  • 186
  • 335