In Ada programming, What is a best practice way to create a 2D array of a size that is specified by the user?
I'm teaching myself Ada for work (after many years of C programming), and I'm having difficulty understanding how to create an array of a size that is only known at runtime...
My simple program needs to do the following.
- Ask the user to type in two numbers, for the width (X) and height (Y) of a 2 dimensional character array.
- Use these values as the upper bounds of the array (0..X-1, 0..Y-1).
- Initialise the array with zeroes.
After quite a bit of googling I think I'm almost there, if I hard code the array to a fixed size then the program works fine, but I'd like to get the array sized as per the user's desire.
My full program is as follows, it doesn't compile, but I hope it is enough to demonstrate what I'm trying to do.
with Ada.Text_IO; use Ada.Text_IO;
with Ada.Integer_Text_IO; use Ada.Integer_Text_IO;
with Ada.Characters; use Ada.Characters;
procedure test is
type Two_Dimensional_Char_Array is array (Integer range <>, Integer range <>) of character;
--grid : Two_Dimensional_Char_Array (0..59, 0..29) := (others => (others => ' '));
grid : Two_Dimensional_Char_Array;
procedure Draw_Grid(scr : Two_Dimensional_Char_Array) is
X, Y : Integer := 0;
begin
Put("Width? ");
Get(X);
Put("Height? ");
Get(Y);
declare
grid : Two_Dimensional_Char_Array(0..X-1, 0..Y-1);
begin
grid := (others => (others => 0));
end;
Put("+");
for X in scr'First(1)..scr'Last(1) loop
Put("-");
end loop;
Put_Line("+");
for Y in scr'First(2)..scr'Last(2) loop
Put("|");
for X in scr'First(1)..scr'Last(1) loop
Put(scr(X, Y));
end loop;
Put_Line("|");
end loop;
Put("+");
for X in scr'First(1)..scr'Last(1) loop
Put("-");
end loop;
Put_Line("+");
end Draw_Grid;
begin
grid(0,0) := 'a';
grid(0,1) := 'b';
grid(1,1) := 'c';
grid(20,10) := 'd';
grid(59,29) := 'X';
Draw_Grid(grid);
end test;