Reputation: 65
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?
Upvotes: 2
Views: 137
Reputation: 1833
int myarray[8];
This is a simple declaration of an Array i.e you are telling the compiler "Hey! I am gonna use an integer array of size 8". Now the compiler knows it exists but it does not contail any values. It has garbage values.
If you intend to initialize array (automatically) then you need to add a blank initialization sequence.
int myarray[8]={}; //this will do
Happy Coding!
Upvotes: 0
Reputation: 1216
If you want to get a array have a initial value,you can do like this:
int *arr = new int[8]();
Upvotes: 1
Reputation: 122373
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] = {};
Upvotes: 11