Ada动态数组分配索引范围

Ada dynamic array allocation index range

我如何更改此代码以强制索引以第一个索引“第一次计算为 1”和最后一个索引“最后一次计算为”长度开始?

  Menu_Text_Ptr := new Packed_Message_Array_Type'("A...",
                                                  "B...",
                                                  "C...",
                                                  "D...");

我有几个这样的动态数组,它们的长度各不相同。我宁愿不给出最后一个索引值的明确长度,因为这会使代码维护变得有点复杂。我宁愿只是从分配语句中添加或减去内容,然后让编译器计算出来。

就目前而言,第一个索引“首先计算为 -2147483648(可能类似于 0x80000000)。

是否可以按照我的要求做?

这是 GNAT 上的 Ada83。

如果您的第一个索引是 -2147483648 (-231),那么您可能将数组类型 Packed_Message_Array_Type 定义为:

type Packed_Message_Array_Type is array(Integer range <>) of Some_Type;

如果将索引类型从 Integer 更改为 Positive(这是 Integer 的子类型,下限为 1),则默认下限将为 1.

一般情况下,如果定义一个数组变量指定其初始值,但不指定下限,则下限将默认为索引类型的下限。

(我删除了这个答案的一部分;我以为你可以只为第一个元素定义一个索引,但是位置关联不能跟在命名关联之后。)

Assuming (as Keith did) that you have a type like this:

type Packed_Message_Array_Type is array(Integer range <>) of Some_Type;

If you don't want to dictate that every array have only positive indexes, but you want this array to start at 1, you could say

declare
    subtype Array_Subtype is Packed_Message_Array_Type(1..4);
begin
    Menu_Text_Ptr := new Array_Subtype'("A...",
                                        "B...",
                                        "C...",
                                        "D...");
end;

Or, if you don't want to hard-code the upper bound:

declare
    Source_Array : constant Packed_Message_Array_Type := 
          ("A...", "B...", "C...", "D...");
    subtype Array_Subtype is Packed_Message_Array_Type(1..Source_Array'Length);
begin
    Menu_Text_Ptr := new Array_Subtype'(Source_Array);
end;

I haven't tested either of these, and in particular I'm not sure the second one will work. (Also, the second one is more likely to use additional time to create an array on the stack and copy it to allocated storage, depending on how good the compiler's optimization is.)