UPDATE : I just found out that there's a standard package Interfaces.C.Pointers
that directly supports C-style pointer arithmetic, and now I see that Marc C.'s accepted answer covers its usage. You can probably ignore my answer, which discusses how you might do pointer arithmetic in Ada if Interfaces.C.Pointers
didn't exist (which, in earlier versions of the language, it doesn't).
If you really want to do C-style pointer arithmetic on Ada access types, you can use the generic package System.Address_To_Access_Conversions
to convert an object pointer type to System.Address
, and the System.Storage_Elements
package to perform C-like arithmetic on System.Address
values.
Note that the target object type is a parameter to the System.Address_To_Access_Conversions
generic package. The package itself defines the access type. You can't define your own access type and use it (at least not directly).
Keep in mind that C pointer arithmetic is defined in units of the size of the pointed-to object. So given:
int arr[10];
int *ptr = &arr[0];
the pointer value ptr + 3
points to arr[3]
, which is three int
-sized chunks of memory past the location to which ptr
points not necessarily three bytes. The "+"
and "-"
operators in System.Storage_Elements
work with offsets in storage elements (which are very likely equivalent to C's "bytes").
So if you have an Ada pointer, um, I mean access value, that refers to an element of an array of Integer
s, then advancing to the next element of that array requires:
- Using
System.Address_To_Access_Conversions
to convert the access type to System.Address
;
- Using the overloaded
"+"
operator in System.Storage_Elements
to add the size of an Integer
in bytes (Integer'Max_Size_In_Storage_Elements
) to the System.Address
value; and
- Using
System.Address_To_Access_Conversions
again to convert the System.Address
value back to your access type.
An alternative might be to write C code to do whatever pointer arithmetic you need, and use Interfaces.C
to call that code from your Ada program.
But it's very likely that you don't need to do pointer arithmetic in Ada. C has pointer arithmetic in the core language; it even defines array indexing in terms of pointer arithmetic. Ada does not. There's rarely a good reason to perform pointer arithmetic in Ada. Just let arrays be arrays, and let the compiler figure out how to generate the best code to access their elements. (That code will likely involve pointer arithmetic on the CPU instruction level.)
my_access
accesses a 5-element array of integers. So, given C semantics,var++
should point to the next 5-element array of integers (probably 1 past the end ofmyarr_var
).Var
points to objects of typeMyarr
, whileMyarr_Var (2)
is an object of typeInteger
.