tags:

views:

253

answers:

2
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 value initialized the dynamic array elements by using the () operator, the output I get is

135368
0
0
0
0

Not sure why the first array element is initialized to 135368.

Any thoughts ?

+6  A: 

My first thought is: "NO...just say NO!"

Do you have some really, truly, unbelievably good reason not to use vector?

 std::vector<int> i(5, 0);

Edit: Of course, if you want it initialized to zeros, that'll happen by default...

Edit2: As mentioned, what you're asking for is value initialization -- but value initialization was added in C++ 2003, and probably doesn't work quite right with some compilers, especially older ones.

Jerry Coffin
I am not trying to make a choice between Vectors and Arrays. I am playing around with arrays and see how they behave. Learning process for a C++ course I am taking :)
captonssj
+3  A: 

I agree with litb's comment. It would appear to be a compiler bug.

Putting your code in a main function and prefixing with:

#include <iostream>
#include <ostream>
using std::cout;
using std::endl;
using std::size_t;

I got five zeros with both gcc 4.1.2 and a gcc 4.4.0 on a linux variant.

Edit:

Just because it's slightly unusual with array type: In a new expression an initializer of () means that the dynamically allocated object(s) are value initialized. This is perfectly legal even with array new[...] expressions. It's not valid to have anything other than a pair of empty parentheses as an initializer for an array new expression, although non-empty initializers are common for for non-array new epxressions.

Charles Bailey
And with MinGW GCC 3.4.5 I get 5 garbage numbers.
Michael Burr