首页 > 解决方案 > 为什么不从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;
}

标签: c++

解决方案


数组的大小从 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 开始计数。


推荐阅读