dynamic array size determined at runtime in ada

后端 未结 2 855
刺人心
刺人心 2020-12-19 04:16

Is it possible to have an array with size that is determined at runtime like so,

Procedure prog is
   type myArray is array(Integer range <>) of Float;         


        
相关标签:
2条回答
  • 2020-12-19 04:48

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

    0 讨论(0)
  • 2020-12-19 05:06

    Sure, 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 the arraySize as an argument into a subprogram and declare and operate on it in that subprogram:

    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 :-), as you need to deal with things like an invalid array size and such.

    0 讨论(0)
提交回复
热议问题