As part of learning Ada, I am working some basic coding challenges. I have come across a situation where I would like to create a fixed-size 2D array of integers (size determined at runtime). My idea was to have a small utility function that could be passed the size of the array, create it, fill it and return it for use in other functions.
How do I do this? The other answers I have seen keep the created array in function-scope and do not return it.
So far, this is my main procedure:
with Ada.Integer_Text_IO;
with Ada.Text_IO;
with Coord;
with Grid;
procedure test is
boundary : Coord.Box;
-- This is the array I want to create and fill
-- Note sure about what I put here for the "initial" size
new_grid : Grid.GridType (0 .. 1, 0 .. 1);
begin
-- This is just for the example, actually these
-- values are calculated from values in a text file
Ada.Text_IO.Put ("X Min?");
Ada.Integer_Text_IO.Get (boundary.min.x);
Ada.Text_IO.Put ("X Max?");
Ada.Integer_Text_IO.Get (boundary.max.x);
Ada.Text_IO.Put ("Y Min?");
Ada.Integer_Text_IO.Get (boundary.min.y);
Ada.Text_IO.Put ("Y Max?");
Ada.Integer_Text_IO.Get (boundary.max.y);
new_grid := Grid.get_grid (boundary);
Grid.print (new_grid);
end test;
And this is the grid.adb
in which is the get_grid
function:
with Ada.Integer_Text_IO;
with Ada.Text_IO;
package body Grid is
function get_grid (bounds : Coord.Box) return GridType is
-- This is the grid I'd like to return
new_grid : Grid.GridType (bounds.min.x .. bounds.max.x, bounds.min.y .. bounds.max.y);
begin
for X in bounds.min.x .. bounds.max.x loop
for Y in bounds.min.y .. bounds.max.y loop
new_grid (X, Y) := X + Y;
end loop;
end loop;
return new_grid; -- Needs to persist outsde this function
end get_grid;
-- Print function removed for clarity (this works)
end Grid;
Grid_Type
is declared in grid.ads
as:
type GridType is array (Integer range <>, Integer range <>) of Integer;
In these files, Coords.Box
is just a simple record that holds X/Y min/max integers.
If I run this and input sensible numbers for the grid size I get a CONSTRAINT_ERROR
.
I've read this answer and this answer and some other less-related answers and I'm just not getting it.
I am new to Ada, but proficient in other languages.