Dynamic array size determined at runtime in ada

Is it possible to have an array with a size that is determined at runtime, for example,

Procedure prog is type myArray is array(Integer range <>) of Float; arraySize : Integer := 0; theArray : myArray(0..arraySize); Begin -- Get Array size from user. put_line("How big would you like the array?"); get(arraySize); For I in 0..arraySize Loop theArray(I) := 1.2 * I; End Loop; End prog; 

Is there any way to achieve this result other than using dynamically linked lists or some other similar structure? Or is there a simple built-in data structure that would be simpler than using dynamically linked lists?

+6
source share
2 answers

Of course, declare it in a block as follows:

 procedure prog is arraySize : Integer := 0; type myArray is array(Integer range <>) of Float; begin -- Get Array size from user. put_line("How big would you like the array?"); get(arraySize); declare theArray : myArray(0..arraySize); begin for I in 0..arraySize Loop theArray(I) := 1.2 * I; end Loop; end; end prog; 

or pass arraySize as an argument to a routine and declare and use it in that routine:

 procedure Process_Array (arraySize : Integer) is theArray : myArray(0..arraySize); begin for I in arraySize'Range Loop theArray(I) := 1.2 * I; end Loop; end; 

This is just illustrative (and not compiled :-) since you need to deal with things like invalid array size, etc.

+6
source

Yes, you can defer a declaration of an object with restrictions until you know the size. In this example, the Candidates array can be allocated in a nested block (entered by the declare keyword) or on the heap (using the new keyword). In this related example, Line each time in a loop has a different size, depending on what Get_Line finds.

+1
source

All Articles