简体   繁体   English

堆上的 C++ 数组声明?

[英]C++ array declaration on heap?

In C++ we can write:在 C++ 我们可以写:

    int arr[] = {20,3,2,0,-10,-7,7,0,1,22};
//Smal Note: Why int *arr = {20,3,2,0,-10,-7,7,0,1,22}; won't work? I learnt I can replace [] with *

but what if I want to allocated arr on heap in one line?但是如果我想在一行中在堆上分配 arr 怎么办?

I tried:我试过了:

    int arr[] = new int {20,3,2,0,-10,-7,7,0,1,22};

In function arguments, int[] means "an array of unknown size", and is technically equivalent to int* .function arguments 中, int[]表示“未知大小的数组”,在技术上等同于int* (when the pointer is interpreted as a pointer to the first integer in an array). (当指针被解释为指向数组中第一个 integer 的指针时)。

But in your declaration, int[] means "an array whose size is determined by the initializer", and that is a very well-known size.但是在您的声明中, int[]的意思是“一个大小由初始化程序确定的数组”,这是一个众所周知的大小。

new int[] does create an array on the heap, but it returns a pointer to the first element. new int[]确实在堆上创建了一个数组,但它返回一个指向第一个元素的指针。 You might notice a similarity here with function arguments - it's easy to convert from an array to a pointer.您可能会注意到这里与 function arguments 的相似之处 - 从数组转换为指针很容易。

std::vector<int> creates an array on the heap too, but the vector object which manages the array can live anywhere. std::vector<int>也在堆上创建一个数组,但是管理数组的向量 object 可以存在于任何地方。 That's often a lot more convenient.这通常更方便。

If you write int arr[] = {20,3,2,0,-10,-7,7,0,1,22};如果你写int arr[] = {20,3,2,0,-10,-7,7,0,1,22}; your arr is usually stored on the stack, just like int a=20, b=3, ...;您的arr通常存储在堆栈中,就像int a=20, b=3, ...; . . In this case, the right-hand side is an initializer, which just tells how int arr[] is initialized.在这种情况下,右侧是一个初始化器,它只是告诉int arr[]是如何初始化的。

On the other hand, if you write int *arr = new int[]{20,3,2,0,-10,-7,7,0,1,22};另一方面,如果你写int *arr = new int[]{20,3,2,0,-10,-7,7,0,1,22}; the array is created on the heap, which can only be accessed via pointers, and the pointer pointing to the array is assigned into int *arr which in turn is on the stack.数组是在堆上创建的,只能通过指针访问,指向数组的指针被分配到int *arr中,而 int *arr 又在堆栈上。

So in the context of declaration, int[] and int* are completely different things.所以在声明的上下文中, int[]int*是完全不同的东西。 But both int[] array and int* array can be accessed using the [] operator, eg arr[2] which is synonymous with *(arr+2) .但是int[]数组和int*数组都可以使用[]运算符访问,例如arr[2]*(arr+2)同义。 And when you use int[] or int* as an argument of a function, they are completely interchangeable.当您使用int[]int*作为 function 的参数时,它们是完全可以互换的。

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

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