c++ - 奇怪的 operator[] 行为
问题描述
在写程序的时候,我打错了。我已经写i[data]
了data[i]
。但是,该程序已成功编译并正常运行。
Operator[] 对数组的行为:
#include <iostream>
using namespace std;
int main()
{
int data[] = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
cout << data[6] << endl; // prints 6
cout << 6[data]; // prints 6
return 0;
}
与指针类似的 operator[] 行为:
#include <iostream>
using namespace std;
int main()
{
char* str = "Hello, world!";
cout << str[9] << endl; //prints 'r'
cout << 9[str]; //prints 'r'
return 0;
}
为什么data[i]
等于i[data]
?
解决方案
i[data]
是相同的*(i + data)
data[i]
是相同的*(data + i)
并且data + i
等于i + data
。
推荐阅读
- html - 如何将输入添加到 sech 栏操作中的链接?
- image - 在 ImageView 中显示相机从图库中捕获的图像时出现问题。它无法显示
- linux - Docker容器mac地址变化
- flutter - 如何通过触摸旋转颤振小部件
- amazon-ec2 - 我可以将 CloudFlare 的代理与 AWS Application Load Balancer 一起使用吗?
- android - 如何在代码中等待,直到从 Firestore 下载所需的数据?
- azure - 在运行时使用 Powershell 在构建管道中重写 YAML 文件配置
- node.js - 如何使用 Promises 在 fs.createReadStream/csv-parser 中使用 await/async?
- linux - 运行脚本后grep日志文件,需要显示日志文件
- firebase - 在 react native 中使用 fetch 进行 API 调用时未触发 Firebase 函数