首页 > 解决方案 > C++ -1 index has value of last index element ? Huh?

问题描述

Can you explain to me what happens here?

It's a mystery to me how it is that -1 index the last element 5.

I know len-1 is correct for the FOR loop but I want to know how it rotates the array.

#include <iostream>
using namespace std;

int main()
    {
    int a[5]={1,2,3,4,5};
    int len = sizeof(a)/sizeof(a[0]);

    for(int i=len;i>=0;i--)
        {
        a[i]=a[i-1]; 
        }

    for(int i = 0;i<len;i++)
        {
        cout<<a[i]<<" ";
        }
    return 0;
    }

output:

5 1 2 3 4

标签: c++gccread-eval-print-loop

解决方案


int len = sizeof(a)/sizeof(a[0]); Will give you 5. Then you do for(int i=len;i>=0;i--){ a[i]=a[i-1]; - which means you do a[5] - but 5 is not a valid index, only [0-4] are valid. So you are accessing out of bounds, which is Undefined Behaviour, so anything could happen.

Btw; why don't you use std::size?


推荐阅读