Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the purpose of "{}" in "new int[5]{};"?

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?

like image 998
Jayesh Avatar asked Oct 13 '17 06:10

Jayesh


People also ask

What is int a {} in C++?

C++ int. The int keyword is used to indicate integers. Its size is usually 4 bytes. Meaning, it can store values from -2147483648 to 2147483647.

What does new int [] mean?

new int[] means initialize an array object named arr and has a given number of elements,you can choose any number you want,but it will be of the type declared yet.

What does int a 5 mean?

int *a[5] - It means that "a" is an array of pointers i.e. each member in the array "a" is a pointer. of type integer; Each member of the array can hold the address of an integer. int (*a)[5] - Here "a" is a pointer to the array of 5 integers, in other words "a" points to an array that holds 5 integers.

What is the use of new int?

Creates a integer array of 'n' elements.


1 Answers

int *arr = new int[5];

performs a default initialization (which in this case means the elements of arr are uninitialized), while

int *arr = new int[5]{};

is a value initialization (which in this case means the elements of arr are zero-initialized). See the corresponding rules in the links. Specifically for the latter case, the array will be zero-initialized.

Anyway, if there is no other good reason, the use of std::vector should be preferred.

Edit: Concerning your second question: This is due to the initialization rules. You would have to write

int* a = new int[5]{1, 1, 1, 1, 1 };

The already recommended std::vector supports the syntax you desire:

#include <iostream>
#include <vector>

int main()
{
    std::vector<int> a(5, 1);
    for(int i = 0; i < 5; i++)
        std::cout<< a[i]<<' ';
}

https://ideone.com/yhgyJg Note however the use of ()-braces here. As vector has an constructor for std::initializer_list, calling vector{ 5, 1} would impose a certain ambiguity, which is resolved by always preferring the initializer_list constructor for {}-initializations if provided. So using { } would cause to create a vector with 2 elements of values 5 and 1, rather than 5 elements of value 1.

like image 168
Jodocus Avatar answered Oct 28 '22 01:10

Jodocus