简体   繁体   English

这两条语句的含义是什么 char (*test)[10]; 测试=新的字符[4][10];

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

In c++ c++

char (*test)[10];

test = new char[4][10];

what the meaning of above two declarations?以上两个声明的含义是什么?

char (*test)[10];

The first line declares test to be a pointer to char[10] .第一行将test声明为指向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 .第二行创建一个char[4][10] ,一个包含 4 个char[10]类型元素的数组,并将指向该数组第一个元素的指针分配给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

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] .然后它在表达式中转换,例如用作初始化表达式以指向其类型为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.为数组分配 memory 的 operator new 也返回指向分配数组第一个元素的指针。 So if you want to allocate an array of the type char[4][10] then you can write所以如果你想分配一个 char[4][10] 类型的数组,那么你可以这样写

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

Here char[10] is the type of elements of the allocated array.这里的char[10]是分配数组的元素类型。 So a pointer to an element of the array has the type char ( * )[10] .因此,指向数组元素的指针的类型为char ( * )[10]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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