c++ dynamic array of pointers [duplicate]

旧城冷巷雨未停 提交于 2019-12-27 07:02:10

问题


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

回答1:


According to the C++ Standard (4.2 Array-to-pointer conversion)

1 An lvalue or rvalue of type “array of N T” or “array of unknown bound of T” can be converted to a prvalue of type “pointer to T”. The result is a pointer to the first element of the array.

So for example if you have an array like this

int a[] = { 1, 2, 3, 4, 5 };

then in this declaration

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

then in expressions with rare exceptions it is converted to pointer to its first element of the type T *.

In this declaration

int **arr = new int*[10]; 

the initializer is an array elements of which has the type int *. You can introduce a typedef or an alias declaration

typedef int * T;

or

using T = int *;

So you can write

T * arr = new T[10]; 

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

That is the operator new returns pointer to the first element of the dynamically allocated array.



来源:https://stackoverflow.com/questions/47925124/c-dynamic-array-of-pointers

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!