c++ - 为什么不从0开始定义多维数组?
问题描述
试图学习 c++,我写了下面的代码,但不明白为什么它不是:
int arrNum[2][2]
代替
int arrNum[3][3]
我认为数组从零开始,所以我有两个高度,两个长度 - 如果你从零开始,对吗?
int main()
{
int arrNum[3][3] = {
{0,5,7},
{1,5,7},
{2,5,7}
};
for (int i = 0; i < 3; ++i) {
for (int j = 0; j < 3; ++j) {
cout << arrNum[i][j] << " ";
}
cout << endl;
}
return 0;
}
解决方案
数组的大小从 1 开始。另一方面,索引从 0 开始。
所以,假设你有一个数组(任何数组):
int arr[2] = {0,1};
在这里,大小是 2,它是这些原始[]
括号中的大小。
另一方面,如果你想在创建数组后访问它,你可以这样做:
std::cout << arr[0]; // ouputs 0
std::cout << arr[1]; // outputs 1
std::cout << arr[2]; // will, among other things, probably crash your program as there
// are only 2 items in the array, but accessing started counting at 0
所以,简而言之,当你访问数组时,你从 0 开始。但是当你声明它们时,你给出了实际大小,它将从 1 开始计数。
推荐阅读
- css - CSS 动画在开发过程中有效,但在网站被推送时停止,为什么?
- flutter - 在颤动中使用流进行分页
- ruby-on-rails - 升级到 ruby 3 和 rails 6.1 后未定义的方法“file_fixture_path”
- html - 如何在 html 页面中排列这些引导元素
- javascript - 函数在 Cloud Functions 中返回未定义、预期的 Promise 或值
- google-api - 如何使用 python 向 Google Hangouts 发送消息?
- c# - c# - 在注册时向身份用户添加角色失败,外键约束
- sql - 基于临时表配置单元的查询
- spring-boot - GCP - 创建虚拟机实例并提取日志
- c++ - 使用 ASIO 协程和网络 TS 使用 C++20 进行同步和结果检索