Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ initializing the dynamic array elements

Tags:

c++

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 ?

like image 405
captonssj Avatar asked Feb 15 '26 13:02

captonssj


1 Answers

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.

like image 198
Jerry Coffin Avatar answered Feb 17 '26 01:02

Jerry Coffin



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!