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};
3
  • 2
    int *arr = new int[]{...};. Commented Apr 12, 2021 at 20:40
  • 1
    "I learnt I can replace [] with *" It should be about function arguments. Commented Apr 12, 2021 at 20:41
  • 1
    You also have the more popular std::vector<int> Commented Apr 12, 2021 at 20:44

2 Answers 2

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.

Sign up to request clarification or add additional context in comments.

Comments

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.