In C++, when you dynamically allocate an array of int
, are the values of the int
s undefined or initialized to 0?
int *array = new int[50];
The term is uninitialized. But it depends how you initialize the array. You could value-initialize it:
int *array = new int[50]();
and the values would be 0.
If you leave it uninitialized, you can't know what values are there because reading from them would be undefined behavior.
If you use vectors instead of arrays, you will get an initial value of 0 for all elements:
std::vector<int> v(50);
If you want a different default value, you can specify one:
std::vector<int> v(50, 42);
An additional benefit of vectors is that you don't have to manually release the underlying array.
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