c++ - 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
解决方案
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?
推荐阅读
- python - 将抓取的 HTML 表转换为 Pandas 数据框
- javascript - 如何将动态生成的代码导入 webworker 以便在调试器中访问
- quarkus - Java 9 是否与休眠 4.3.5.Final 兼容?
- javascript - 如何修复导航栏
- docker - 执行`sudo apt-get update`命令时无法连接到ports.ubuntu.com:80
- python - flask-sqlachemy 外键不适用于模型
- amazon-web-services - 关闭 ECS 实例时是否需要在 AWS 中卸载 EBS 卷?
- php - 将多对多关系值传递给 vue 文件
- python-3.x - pymongo.errors.WriteError:更新路径“更新”会在“更新”处产生冲突
- php - 作为开发人员,我如何在 Moodle 中进行调试?