数组索引从 Ada 中不等于 1 的值开始

Array indices start from a value not equals 1 in Ada

我有一个关于在 Ada 中实现对数组的访问函数的作业。 然而,数组的声明让我很沮丧:

A: array[1..15, 5..20] of integer;

网上找了很多关于Ada多维数组的资料,但是都没有提到这种情况下的内存分配。它只是 1..15 到 5..20 的简单映射吗?或者,程序实际上跳过数组每一行中的前 4 个元素并保持内存空白?如果我尝试访问 A[1, 3] 会怎样?

The Ada 2012 specification states:

  • The possible values for a given index are all the values between the lower and upper bounds, inclusive; this range of values is called the index range.
  • The bounds of an array are the bounds of its index ranges.
  • The length of a dimension of an array is the number of values of the index range of the dimension (zero for a null range).

关于内存表示,the section of the specification concerned with array operations states 数组范围的长度由其上限减去下限加上 1(这是对第三个要点的重述以上)。

有了这些知识,我们可以回答您的问题:

Is it just simple mapping of 1..15 to 5..20?

存在索引到内部数组范围位置的隐式映射,但您的映射不正确。

array[ 1..15, 5..20]:

  • 一维数组范围长度是15 - 1 + 1,所以15个元素长。
  • 二维数组范围长度是20 - 5 + 1,所以16个元素长。

Or, program actually skips first 4 elements in each row of the array and keeps memory blank?

否,根据规范,系统不会为定义范围内无法访问的数组元素分配 space。

What if I try to access A[1, 3]?

规范声明将根据数组初始化的范围执行索引边界检查,假设 1,3 超出范围 [1..15,5..20] 这将导致运行时索引出- 越界错误。