David Mirakian
David Mirakian

Reputation: 23

Ada dynamically allocated array in an array cannot be initialized at compile time

I am trying to create an array that stores 3 dynamically allocated arrays of floats. When I try to allocate the three arrays later in my program, the compiler tells me it was expecting "Float_Array", but "found type access to subtype of "Float_Array"". I am not sure if this issue comes from me using a pointer here or if it is because I am creating an array containing a dynamic array.

Here are my array definitions:

      type Float_Array is array (Integer range <>) of Float;
      type Triangle_Array is array (0..2) of Float_Array;
      type Triangle_Array_Ptr is access Triangle_Array;

This is the code that is causing issues:

      V(0) := new Float_Array(0..Size-1);
      V(1) := new Float_Array(0..Size-1);
      V(2) := new Float_Array(0..Size-1);

Edit: V is a Triangle_Array_Ptr Thank you Zerte for the clarification on line 2 of my code, I didn't realize that was a rule for arrays. Is there a different way to contain three dynamic Float_Arrays? If not I can just create three independent Float_Arrays and pass them to each method.

Upvotes: 2

Views: 136

Answers (1)

Simon Wright
Simon Wright

Reputation: 25491

You can’t create an array of indefinitely-sized objects, and you’re right that an approach to this uses dynamic memory. However, the thing that needs to be dynamically allocated is the indefinitely-sized object; you need a Float_Array_Ptr, which is fixed-size, so you can create arrays as required.

type Float_Array is array (Positive range <>) of Float;
type Float_Array_Ptr is access Float_Array;
type Triangle_Array is array (1 .. 3) of Float_Array_Ptr;
V : Triangle_Array
  := (1 => new Float_Array'(1 .. 3 => 1.0),
      2 => new Float_Array'(1 .. 2 => 2.0),
      3 => new Float_Array'(1 .. 1 => 3.0));

which as you see lets you create a ragged array of arrays of Float.


On the other hand, if all the Float_Arrays in any particular case are the same length, perhaps you could use a two-dimensional array and not allocate memory at all?

type Triangle_Array 
  is array (Positive range <>, Positive range <>) of Float;
V : Triangle_Array (1 .. 3, 1 .. 5)
  := (1 => (others => 1.0),
      2 => (others => 2.0),
      3 => (others => 3.0));

Upvotes: 6

Related Questions