Im new to this forum and I want to ask why it is that the behavior of this array Im making is different from I expected it to be?.
int main() {
int array[8]={3,5,5,6,6,5,3,5};
for(int i=-1;i<=8;i+=2) {
std::cout<<array[i+1];
}
return 0;
}
The output of this is: 35637
I didn't know why the result is like this especially the last part in the index 8 which is the value is 7...
Your array has 8 entries, with the following positions:
array[8] = {3, 5, 5, 6, 6, 5, 3, 5}
^ ^ ^ ^ ^ ^ ^ ^
(position) 0 1 2 3 4 5 6 7
Your loop starts at i = -1
, goes until i <= 8
, and increases i
by 2 each time, so i
takes the values -1, 1, 3, 5, and 7. Since you're accessing the elements array[i+1]
, you're asking for the elements at positions 0, 2, 4, 6, and 8. But there's no position 8, so this is an error and the program's behavior becomes undefined by including it, meaning literally anything could happen, even at a different place from the illegal call itself (this is obviously very bad and must always be avoided).
In your case, it appears that your program is reading whatever is in the memory right after the end of the array. You got a 7 there by chance -- there could be anything there, and in fact your program may not even be allowed to access that memory in which case it will crash with a segmentation fault.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With