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?
-
3This should sum up why they aren't zeroed: chat.stackoverflow.com/transcript/message/10771489#10771489Qaz– Qaz2013年07月23日 02:25:56 +00:00Commented Jul 23, 2013 at 2:25
-
local variables are not default initializedassem– assem2013年07月23日 02:28:08 +00:00Commented Jul 23, 2013 at 2:28
-
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). What made you assume that? (I just mean, lets not assume lets play safe and stick to what the doc says)Suvarna Pattayil– Suvarna Pattayil2013年07月23日 08:41:29 +00:00Commented Jul 23, 2013 at 8:41
4 Answers 4
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] = {};
1 Comment
Initial values are not guaranteed to be 0.
2 Comments
If you want to get a array have a initial value,you can do like this:
int *arr = new int[8]();
Comments
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!