captonssj
captonssj

Reputation: 311

C++ initializing the 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 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 ?

Upvotes: 2

Views: 2533

Answers (2)

Jerry Coffin
Jerry Coffin

Reputation: 490108

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.

Upvotes: 6

CB Bailey
CB Bailey

Reputation: 791691

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.

Upvotes: 3

Related Questions