问题描述
我试图了解如何在C ++中创建动态指针数组.我知道new
返回指向分配的内存块的指针,而int*[10]
是指向int
的指针的数组.但是,为什么要将其分配给int**
?我正在努力了解这一点.
I'm trying to understand how to create a dynamic array of pointers in C++.I understand that new
returns a pointer to the allocated block of memory and int*[10]
is an array of pointers to int
. But why to you assign it to a int**
? I'm struggling to understand that.
int **arr = new int*[10];
推荐答案
根据C ++标准(4.2数组到指针的转换)
According to the C++ Standard (4.2 Array-to-pointer conversion)
例如,如果您有一个像这样的数组
So for example if you have an array like this
int a[] = { 1, 2, 3, 4, 5 };
然后在此声明中
int *p = a;
用作初始化程序的数组指示符将隐式转换为指向其第一个元素的指针.
the array designator used as the initializer is implicitly converted to pointer to its first element.
所以一般来说,如果你有数组
So in general if you have array
T a[N];
然后在极少数例外的表达式中将其转换为指向类型为T *
的第一个元素的指针.
then in expressions with rare exceptions it is converted to pointer to its first element of the type T *
.
在此声明中
int **arr = new int*[10];
初始化程序是一个数组元素,其类型为int *
.您可以引入typedef或别名声明
the initializer is an array elements of which has the type int *
. You can introduce a typedef or an alias declaration
typedef int * T;
或
using T = int *;
所以你可以写
T * arr = new T[10];
即指针arr
指向动态分配的数组的第一个元素.由于数组元素的类型为int *
,因此指向数组元素的指针的类型为int **
.
that is the pointer arr
points to the first element of the dynamically allocated array. As the elements of the array has the type int *
then the type of the pointer to an element of the array is int **
.
这是new运算符,它返回指向动态分配数组的第一个元素的指针.
That is the operator new returns pointer to the first element of the dynamically allocated array.
这篇关于c ++动态指针数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!