0

In C++ we can write:

    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?

I tried:

    int arr[] = new int {20,3,2,0,-10,-7,7,0,1,22};
trincot
  • 317,000
  • 35
  • 244
  • 286

2 Answers2

1

In function arguments, int[] means "an array of unknown size", and is technically equivalent to int*. (when the pointer is interpreted as a pointer to the first integer in an array).

But in your declaration, int[] means "an array whose size is determined by the initializer", and that is a very well-known size.

new int[] does create an array on the heap, but it returns a pointer to the first element. You might notice a similarity here with function arguments - it's easy to convert from an array to a pointer.

std::vector<int> creates an array on the heap too, but the vector object which manages the array can live anywhere. That's often a lot more convenient.

MSalters
  • 173,980
  • 10
  • 155
  • 350
0

If you write 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, ...;. In this case, the right-hand side is an initializer, which just tells how int arr[] is initialized.

On the other hand, if you write 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.

So in the context of declaration, int[] and int* are completely different things. But both int[] array and int* array can be accessed using the [] operator, e.g. arr[2] which is synonymous with *(arr+2). And when you use int[] or int* as an argument of a function, they are completely interchangeable.