If we write something like:
int *arr = new int[5];
In this case, the system dynamically allocates space for 5 elements of type int
and returns a pointer to the first element of the sequence.
But, once I saw the following code:
int *arr = new int[5]{};
So, What does mean {}
after new
operator? What is the purpose of {}
in this code?
I have initialized array with my own value, like this:
#include <iostream>
int main()
{
int* a = new int[5]{1};
for(int i = 0; i < 5; i++)
std::cout<< a[i]<<' ';
delete[] a;
}
Output:
1 0 0 0 0
Only first element print 1
. Why?
new
reference. In the table describing the syntax, note the initializer part. Then scroll down to the section about Construction to read more about it. – Radiogram