Search code examples
adagnat

Ada Syntax for initializing dynamically allocated array


What is the correct syntax for initializing a dynamically allocated array in Ada? I have tried this:

type Short_Array is array (Natural range <>) of Short;
Items : access Short_Array;
Items := new Short_Array(1..UpperBound)'(others => 0);

which results in a compiler error - "binary operator expected". And this:

type Short_Array is array (Natural range <>) of Short;
Items : access Short_Array;
Items := new Short_Array(1..UpperBound);
Items.all := (others => 0);

which seems to raise a SEGFAULT surprisingly. Not sure what's going on there but wanted to get the syntax right before I start chasing my tail.


Solution

  • If you are using Ada2012 you can do the following:

    type Short_Array is array(Natural range <>) of Short with
       Default_Component_Value => 0;
    Items : access Short_Array := new Short_Array(1..UpperBound);
    

    The use of default initial values for arrays is explained in section 2.6 of the Ada 2012 Rationale http://www.ada-auth.org/standards/12rat/html/Rat12-2-6.html