+ 3

Hey friends !Please explain me this code and say why its output is 36?

#include <iostream> using namespace std; int main() { int const N =4; int x[N]={1,1,1,1}; cout<<x[N]; return 0; } // outputs 36 but why if I write N=3,then output will be 3 why buddy ?

6th Sep 2018, 7:27 PM
Albert Whittaker :Shaken To Code
Albert Whittaker :Shaken To Code - avatar
2 Antworten
+ 3
it intializes an array of size N However the indices start from 0 and go to N-1 So x[N] actually accesses the memory just after the array, which is some garbage value. But I also don't know why it always shows the same garbage values :/
6th Sep 2018, 7:38 PM
Matthias
Matthias - avatar
+ 3
Array indexes start from zero (0, 1, 2...) the array is 4 ints big which means 3 is the highest one. C and C++ dont check if the array index is out of range and gives you a value in memory after the array (random value basically).
6th Sep 2018, 7:40 PM
TurtleShell
TurtleShell - avatar