Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Behavior of Arrays in a Loop

Tags:

c++

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...

like image 560
Jomarie Cajes Avatar asked Dec 17 '22 20:12

Jomarie Cajes


1 Answers

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.

like image 152
Baryons for Breakfast Avatar answered Jan 18 '23 07:01

Baryons for Breakfast