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?
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.
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.
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.
Creates a integer array of 'n' elements.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With