Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ada array access: Pointer to a specific item within the array, the position being dynamic based on input parameters.

Tags:

pointers

ada

I'm working in Ada95, and I'm having difficulty figuring out pointers.

I have code that looks like the following:

type vector is array (1 .. 3) of integer;   
type vector_access is access vector;

my_vec : vector;

procedure test is  
  pointer : vector_access := my_vec'access;  
begin   
  ...  
end;

This fails compilation on the definition of pointer, saying

"The prefix to 'ACCESS must be either an aliased view of an object or denote a subprogram with a non-intrinsic calling convention"

If I then change the definition of the vector itself to:

my_vec : aliased vector  

it now returns the compiler error:

"The expected type for X'ACCESS, where X denotes and aliased view of an object, must be a general acces type"

At the end of the day what I really need is a pointer to a specific item within the array, the position being dynamic based on input parameters. Can anyone point me in the right direction?

like image 752
Bryan Avatar asked Dec 05 '25 15:12

Bryan


1 Answers

If you're using GNAT, the error message after the "must be a general access type" should have given you the solution:

add "all" to type "vector_access" defined at line ...

so that you would end up with:

type Vector_Access is access all Vector;

The use of "all" to designate a general access type has to do with dynamic memory allocation pools in Ada. If you don't care about dynamic memory allocation pools, then don't worry about it, and just include "all" in your access type definitions.

I'm not sure if this is part of what you're looking for at the end of the day, but you are aware that in most circumstances Ada's access (pointer) types are used to handle dynamically allocated memory, right?

So instead of pointing my_vec at an aliased variable, you would dynamically allocate it:

Pointer_2_Dynamic : vector_access := new Vector;

This way you can dynamically allocate at runtime the objects you need, and easily handle variably sized ones (though you'd need a different vector definition to accomplish that:

type Dynamic_Vector is array (Natural range <>) of Integer;
type Dynamic_Vector_Access is access Dynamic_Vector;

N : Natural := 10; -- Variable here, but could be a subprogram parameter.
Dyn_Vector : Dynamic_Vector_Access := new Dynamic_Vector(1..N);
like image 130
Marc C Avatar answered Dec 07 '25 17:12

Marc C