数组的索引大小

Index size of an array

本文关键字:索引 数组      更新时间:2023-10-16

如果我有一个像a[100]这样的数组,我从10开始。当我声明int a[100]时,我的数组有多长?

它总是从0开始计数?如果是,它将是一个带有101空格的数组。

#include <iostream>
using namespace std;
int main()
{
float time[20]; //
int a, first = 20, y, x;
for (x = 1; x < 21; x++) {
cout << "Enter the time of the person number " << x << " : ";
cin >> time[x];
}
for (y = 1; y < 20; y++) {
if (time[y] < first) {
first = time[y];
a = y;
}
}
getchar();
cout << "The person " << a << " was the faster.";
cout << time[1];
getchar();
return 0;
}

这里从1开始.

如果我更改它将从0开始.

for (x=0;x<21;x++)
for (y=0;y<20;y++)

为什么从0开始要好得多?

C++使用0索引,因此,对于int a[20];有效索引为0,..,19。

a[20]确实超出界外访问,导致 UB。

"当我声明 int a[100] 时,我的数组有多长">

它的大小为 100 个元素。 有效索引通过a[99](包括两者)a[0]。索引a[100]超过数组的末尾(越界)。

在 c++ 中,数组总是从 0 索引开始,你在括号中传递的数字是数组的大小。 如果你写,int A[10]...这意味着您可以在数组中存储 10 个元素,但索引从 0 开始,一直到 9。