简体   繁体   English

关于C++中动态多维数组结构的一个小问题

[英]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?在这个动态多维数组的声明中,这种 [4] 的重复究竟做了什么?

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.那么 T 是数组元素的类型。

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现在让我们通过以下方式将T定义为 typedef 名称

typedef int T[4];

or或者

using T = int[4];

So this declaration所以这个声明

T *array = new T[10];

is valid also and for this typedef.也适用于这个 typedef。

Now let's substitute T for its typedef definition in the reversed way.现在让我们用相反的方式用 T 代替它的 typedef 定义。 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.因此运算符 new 分配了一个具有 10 个“行”的二维数组,每个“行”又是一个由 4 个 integer 元素组成的数组。

This record这个记录

int ( *array )[4] 

means pointer to an array (element of the two-dimensional array) of 4 elements.表示指向 4 个元素的数组(二维数组的元素)的指针。

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 ) .要获取指向数组元素类型的指针,只需将记录( a[N1] )替换为( *p ) For example例如

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

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

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