1

Dynamic arrays are allocated in C++ like this.

int *arr = new int(5);
int *arr = new int[5];

What is the difference between these ways? Or Are they exactly same?

1
  • 2
    The second is a pointer to dynamic allocated int array of size 5. The first is a pointer to an int with 5 as its value. Nov 25, 2020 at 16:03

1 Answer 1

6

An array is only created when you use []. If you are not using [], then you are not creating an array.

int *arr = new int(5); allocates a single int and gives it the value of 5.

int *arr = new int[5]; allocates an array of 5 int's with no specified value in each element.

1
  • This answers my question. Thanks.
    – suyashky
    Nov 25, 2020 at 16:14

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.