2016-12-02 70 views
1

在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令人驚訝。不知道那裏發生了什麼,但是想在我開始追逐我的尾巴之前獲得語法。

+0

你爲什麼要動態分配一個數組? –

+0

你的第二個版本在這裏工作得很好,macOS,GNAT GPL 2015/2016。你使用的是什麼操作系統/編譯器? –

+0

@JimRogers它是一個記錄類型的一部分,我不知道在編譯時的大小。 –

回答

5

如果您正在使用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

完美運作。謝謝! –

3

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; 

該記錄在堆棧上動態分配進行分配。如果記錄大小非常大,您將遇到堆棧溢出問題。如果不是,這個效果很好。這種方法的一個優點是當到達塊的末尾時實例會自動解除分配。