Home > Blockchain >  What is the meaning of these two statements char (*test)[10]; test = new char[4][10];
What is the meaning of these two statements char (*test)[10]; test = new char[4][10];

Time:09-27

In c

char (*test)[10];

test = new char[4][10];

what the meaning of above two declarations?

CodePudding user response:

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

CodePudding user response:

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].

  • Related