+ 3
What the heck is happening?
2 Answers
+ 7
In your main, you do :
int myarr[2];
//Initialize an array of 2 integers.
//Thus, you reserve memory for two integers.
for(int x=0;x<5;x++)
//Move a variable 'x' from 0 to 4.
cout<<x<<":"<<myarr[x];
// Print the values one by one.
/*
Now, the array is declared for 2 ints. But since you haven't set any values, random garbage values are printed. Further, myarr[2], myarr[3], and myarr[4] do not exist, as they are uninitialized. So you get garbage values instead.
*/
+ 2
Kinshuk has already explained it but still..
You declared an array. i.e. You reserved memory for 2 integers as in array. Now the memory block allocated had some previously garbage value. So it is printing those garbage values. Similar argument for further since the array index 2,3... don't exist the garbage at their location(2 bytes after last array index) is printed