Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

I got a trouble with C++ array initialization

Tags:

c++

arrays

I am new to C++. Recently, I have been stuck with a simple code of C++ features. I will be very grateful if you can point out what exactly the problem. The code as follows:

// used to test function of fill
#include<iostream>
#include<algorithm>
using namespace std;
int main(){
   int val = 0;
   int myarray[8];
   //fill(myarray,myarray+2,1);
   for(;val < 8;++val){
      cout << myarray[val];
      cout << endl;
      }
}

And the it has printed out:

-887974872
 32767
 4196400
 0
 0
 0
 4196000
 0

The question is I thought the default value for array without initialization (in this case its size is 8) would be (0,0,0,0,0,0,0,0). But there seemed to be some weird numbers there. Could anyone tell me what happened and why?

like image 876
nicknguyen128 Avatar asked Jun 08 '26 13:06

nicknguyen128


1 Answers

The elements are un-initialized, i.e, they contain garbage value.

If you want to initialize the array elements to 0, use this:

int myarray[8] = {};
like image 52
Yu Hao Avatar answered Jun 11 '26 22:06

Yu Hao



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!