+ 3

Unexpected Output of array in c++

in this statement the is expected to be 0 but it's 8!(like my code named "arr").why? int b[6] = {12, 35, 212, 17, 9}; cout<< b[6] << endl;

17th Jul 2018, 8:27 PM
🇮🇷🇮🇷Mohsen🇮🇷🇮🇷
🇮🇷🇮🇷Mohsen🇮🇷🇮🇷 - avatar
4 Answers
+ 6
The memory you are trying to access is out of the bounds of the array. You haven't assigned a value to it, so you get whatever was stored in that memory cell before, which is not necessarily 0.
17th Jul 2018, 9:10 PM
Shadow
Shadow - avatar
+ 4
Mohsen you have defined an array b of size 6 and are trying to access the 7th element which does not exist. Remember that array indexes start from 0. The value of 8 that you get may be from a random area of memory. This type of out of bounds access can also generate an error.
19th Jul 2018, 7:53 AM
Sonic
Sonic - avatar
+ 4
thanks Naitomea & Sonic. but when does it store 8 value so it accidently use it?!
19th Jul 2018, 11:14 AM
🇮🇷🇮🇷Mohsen🇮🇷🇮🇷
🇮🇷🇮🇷Mohsen🇮🇷🇮🇷 - avatar
+ 3
array indexes starts from 0 , and you are not storing anything at 6th position , that's why
19th Jul 2018, 1:56 PM
Tarika
Tarika - avatar