Ada用于初始化动态分配数组的语法
问题描述:
在Ada中初始化动态分配数组的正确语法是什么?我试过这个:Ada用于初始化动态分配数组的语法
type Short_Array is array (Natural range <>) of Short;
Items : access Short_Array;
Items := new Short_Array(1..UpperBound)'(others => 0);
这会导致编译器错误 - “二元运算符预期”。而这:
type Short_Array is array (Natural range <>) of Short;
Items : access Short_Array;
Items := new Short_Array(1..UpperBound);
Items.all := (others => 0);
这似乎提高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);
数组使用默认的初始值是在阿达2012理由http://www.ada-auth.org/standards/12rat/html/Rat12-2-6.html
+0
完美运作。谢谢! –
答
2.6节解释了艾达的另一种方法是将记录定义为判别式记录,判别式决定数组字段的大小。
type Items_Record (Size : Natural) is record
-- Some non-array fields of your record
Items : Short_Array(1..Size);
end record;
记录的实例可以然后在内部块
Get(Items_Size);
declare
My_Record : Items_Record(Size => Items_Size);
begin
-- Process the instance of Items_Record
end;
该记录在堆栈上动态分配进行分配。如果记录大小非常大,您将遇到堆栈溢出问题。如果不是,这个效果很好。这种方法的一个优点是当到达块的末尾时实例会自动解除分配。
你为什么要动态分配一个数组? –
你的第二个版本在这里工作得很好,macOS,GNAT GPL 2015/2016。你使用的是什么操作系统/编译器? –
@JimRogers它是一个记录类型的一部分,我不知道在编译时的大小。 –