C ++ initialization of dynamic array elements
const size_t size = 5;
int *i = new int[size]();
for (int* k = i; k != i + size; ++k)
{
cout << *k << endl;
}
Even though I have a value initialized with the elements of a dynamic array using the () operator, the output I get is
135368 0 0 0 0
Not sure why the first element of the array is initialized to 135368.
Any thoughts?
source to share
My first thought is " NO ... just say NO !"
Do you have a really, really, incredibly good reason not to use a vector?
std::vector<int> i(5, 0);
Edit: Of course, if you want it to be initialized to zeros, this will happen by default ...
Edit2: As mentioned, requested value initialization - but value initialization was added in C ++ 2003 and is probably not quite correct with some compilers, especially older ones.
source to share
I agree with the comments. This will be a compiler error.
Put your code in a function main
and prefix:
#include <iostream>
#include <ostream>
using std::cout;
using std::endl;
using std::size_t;
I got five zeros with gcc 4.1.2 and gcc 4.4.0 on linux variant.
Edit:
Simply because this is a bit unusual with an array type: in a new expression, an initializer ()
means that a dynamically allocated object is value-initialized. This is perfectly legal even with array expressions new[...]
. It is not valid to have anything other than a pair of empty parentheses as an initializer for an array expression new
, although inelastic initializers are common to non-array new
epxressions.
source to share