LambdaBeta
LambdaBeta

Reputation: 1505

Array of strings in Ada record

I have the following record in some Ada code:

type My_Type (Width, Height : Positive) is 
    record
        Data : array (1 .. Height) of String (1 .. Width);
        --  Some other stuff
    end record;

Of course I can't have anonymous arrays in my record, but I can't come up with a way to name the array beforehand.

I know that I could make the package depend on width and height to redefine the string of the correct length and name an array of them, but that makes it clunky to have many different sized records at once (which I want).

Does anybody know of a more elegant solution to the problem?

Note: a 2-D array of characters would work, but only if I could extract strings from it in a straightforward way, which is again something I'm not sure how to do.

Upvotes: 1

Views: 874

Answers (1)

Jim Rogers
Jim Rogers

Reputation: 5021

There are several possible solutions to your problem, including the use of unbounded strings. Below is a solution using a generic package:

generic
   width : Positive;
   height : Positive;
package Gen_String_Matrix is
   Subtype My_String is String(1..width);
   type My_Matrix is array(1..height) of My_string;
end Gen_String_Matrix;

An example of using this package is:

with Ada.Text_IO; use Ada.Text_IO;
with gen_string_matrix;

procedure Gen_String_Main is
   package My_Matrices is new Gen_String_Matrix(width  => 3,
                                                height => 10);
   use My_Matrices;
   Mat : My_Matrices.My_Matrix;
begin
   for Str of Mat loop
      Str := "XXX";
   end loop;
   for Str of Mat loop
      Put_Line(Str);
   end loop;
end Gen_String_Main;

Upvotes: 4

Related Questions