2

I am new to Ada, and I changed from java to Ada. I know how to create an indefinite array. But I would like to create an array like [[],[3],[3,5],[2,3,5]. And I would like to return an Array like this. I cannot find the answer on the Internet.

2 Answers 2

4

You could make an array of pointers to indefinite arrays:

type A is array (Natural range <>) of Integer;
type A_Access is access A;
type AA is array (Natural range <>) of A_Access;

but then you have to deallocate the A_Accesses (if you care, e.g. if the data is set up at the start of the program and doesn’t change).

Or, you could use Vectors:

package V is new Ada.Containers.Vectors
  (Index_Type   => Natural,
   Element_Type => Integer);
subtype A is V.Vector;
type AA is array (Natural range <>) of A;
Sign up to request clarification or add additional context in comments.

2 Comments

Thank you for your help. But when I would like to set V3 : AA. The error appears "Unconstrained subtype not allowed (need initialization)/ provide initial value or explicit array bounds" So I would like to ask can I initialize the V3 as empty and append the array during the loop?
To do that, use Álex’s answer 3.
3

Expanding Simon answer, and assuming you do not want to manually play with pointers, you have three options with standard containers:

  1. An array of vectors (Simon's answer)
  2. A Vector of indefinite arrays.
  3. A vector of vectors.

Arrays are immutable in size. You can concatenate them and extract slices to another array or as arguments, but they cannot grow or shrink, which makes them a complicated choice for record members depending on what you want them for. There are ways around it if you're set on using arrays, but I wouldn't recommend going that route for a newcomer.

With options 2 and 3, you don't have that constraint as Vectors can be resized freely.

For 2:

type A is array (Natural range <>) of Integer;
package V is new Ada.Containers.Indefinite_Vectors (Natural, A);

Now V.Vector variables can grow, and their elements replaced (but not grown in place).

For 3:

package V is new Ada.Containers.Vectors (Natural, Integer);
package VV is new Ada.Containers.Vectors (Natural, V.Vector);

I hope you get the idea.

As for the difference between Vectors and Indefinite_Vectors, the former means that the elements cannot have unknown constraints at compile time (like an array length). This difference is one of the central concepts in Ada so I'd advice to read about it or you'll suffer with arrays/strings. E.g., here: https://en.wikibooks.org/wiki/Ada_Programming/Type_System#Indefinite_subtype

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.