在Ada中初始化动态分配的数组的正确语法是什么?我试过这个:
type Short_Array is array (Natural range <>) of Short;
Items : access Short_Array;
Items := new Short_Array(1..UpperBound)'(others => 0);
Run Code Online (Sandbox Code Playgroud)
这导致编译器错误 - "二元运算符预期".还有这个:
type Short_Array is array (Natural range <>) of Short;
Items : access Short_Array;
Items := new Short_Array(1..UpperBound);
Items.all := (others => 0);
Run Code Online (Sandbox Code Playgroud)
这似乎令人惊讶地提升了一个SEGFAULT.不知道那里发生了什么,但想在我开始追逐我的尾巴之前得到正确的语法.
如果您使用的是Ada2012,则可以执行以下操作:
type Short_Array is array(Natural range <>) of Short with
Default_Component_Value => 0;
Items : access Short_Array := new Short_Array(1..UpperBound);
Run Code Online (Sandbox Code Playgroud)
在Ada 2012 Rationale的第2.6节中解释了数组的默认初始值的使用http://www.ada-auth.org/standards/12rat/html/Rat12-2-6.html
Ada 中的另一种方法是将记录定义为判别式记录,判别式确定数组字段的大小。
type Items_Record (Size : Natural) is record
-- Some non-array fields of your record
Items : Short_Array(1..Size);
end record;
Run Code Online (Sandbox Code Playgroud)
然后可以在内部块中分配记录的实例
Get(Items_Size);
declare
My_Record : Items_Record(Size => Items_Size);
begin
-- Process the instance of Items_Record
end;
Run Code Online (Sandbox Code Playgroud)
该记录在堆栈上动态分配。如果记录大小非常大,您将遇到堆栈溢出问题。如果没有,这个方法效果很好。这种方法的优点之一是,当到达块末尾时,实例会自动取消分配。