Pointers in Ada

Language: Ada

Ada supports pointers, allowing you to pass references to values and records within your program.

Example

We’ll show how pointers work in contrast to values with two procedures: zeroval and zeroptr. zeroval has an Integer parameter, so arguments will be passed to it by value. zeroval will get a copy of ival distinct from the one in the calling procedure.

procedure Zeroval (Ival : in out Integer) is
begin
   Ival := 0;
end Zeroval;

zeroptr in contrast has an access parameter, meaning that it takes a pointer to an Integer. The Ptr.all code in the procedure body then dereferences the pointer from its memory address to the current value at that address. Assigning a value to a dereferenced pointer changes the value at the referenced address.

procedure Zeroptr (Ptr : in out access Integer) is
begin
   Ptr.all := 0;
end Zeroptr;

Main procedure demonstrating the usage:

with Ada.Text_IO; use Ada.Text_IO;

procedure Main is
   I : Integer := 1;
   Ptr : access Integer := I'Access;
begin
   Put_Line ("initial: " & Integer'Image (I));
   
   Zeroval (I);
   Put_Line ("zeroval: " & Integer'Image (I));
   
   Zeroptr (Ptr);
   Put_Line ("zeroptr: " & Integer'Image (I));
   
   Put_Line ("pointer: " & Ptr'Image);
end Main;

To compile and run the Ada program, use the following commands:

$ gnat make main.adb
$ ./main

After running the program, you should see the following output:

initial:  1
zeroval:  0
zeroptr:  0
pointer: access 0

The zeroval procedure doesn’t change the i in main, but zeroptr does because it has a reference to the memory address for that variable.

Now that we can work with pointers in Ada, let’s learn more about the language.