3

I just need to understand what the differences between these are:

int *p = new int[5];

and

int *p = new int(5);
Aykhan Hagverdili
  • 28,141
  • 6
  • 41
  • 93
SirKappe
  • 55
  • 1
  • 7
  • 3
    an array of 5 un-initialized ints vs 1 int initialized to 5 – Borgleader Mar 23 '19 at 18:48
  • 1
    The difference is you shouldn't use either of them in modern C++ code. Instead use `std::vector` or some other kind of Standard Library container. – tadman Mar 23 '19 at 19:01

1 Answers1

10

One creates an array of five ints and assigns a pointer to this array's first element to p. None of the integers in this array are initialized:

int *p = new int[5]; // a pointer to an array of 5 integers

The other one creates a single int, and assigns a pointer to that int to p. This integer is initialized with 5:

int *p = new int(5); // a pointer to an int

As tadman points out in his comment, in essence, the difference is between the operator new and operator new[]. new[] allocates an array and must be deleted with delete[], while new allocates a single object and must be deleted with delete. If you delete with the wrong operator, what happens is undefined behavior. Of course, unless you are a library implementer, you should generally prefer smart pointers and library containers over new and new[].

Aykhan Hagverdili
  • 28,141
  • 6
  • 41
  • 93
  • Important lesson here is the difference between [`operator new`](https://en.cppreference.com/w/cpp/memory/new/operator_new) and `operator new[]`. – tadman Mar 23 '19 at 19:00