What does "new int(100)" do?

JASON picture JASON · Dec 10, 2012 · Viewed 62.5k times · Source

Possible Duplicate:
is this a variable or function

I mistakenly used something like:

int *arr = new int(100);

and it passes compile, but I knew this is wrong. It should be

int *arr = new int[100];

What does the compiler think it is when I wrote the wrong one?

Answer

NPE picture NPE · Dec 10, 2012

The first line allocates a single int and initializes it to 100. Think of the int(100) as a constructor call.

Since this is a scalar allocation, trying to access arr[1] or to free the memory using delete[] would lead to undefined behaviour.