12.3 Pointer Arithmetic

It was noted above that operations (other than assignment) on pointer variables are not allowed. However, the pseudo-module SYSTEM contains the function procedures ADDADR, SUBADR and DIFADR for manipulating address variables. Although these take parameters and return values of type ADDRESS, the parameters are value parameters, not variable parameters. Thus, the assignment compatibility between pointer types and address types means that these function procedures can be applied to pointers and can return values to be assigned to pointers in expressions. In addition, these items are in SYSTEM, and would not necessarily be limited by such considerations, in any case, as the routines of SYSTEM can almost be expected to behave by unique rules. Here are some fragments of correct code:

FROM SYSTEM IMPORT
  ADDRESS, ADR, ADDADR, SUBADR, DIFADR;

VAR
  point, point2 : POINTER TO INTEGER;
  addr : ADDRESS;
  int : INTEGER;

BEGIN
  point := ADDADR (point,  10);    
  point := SUBADR (point,  10); 
  int := DIFADR (point, point2);

It is important to note that manipulating pointers in this fashion requires a thorough knowledge of the specific machine being used and particularly the manner in which it uses addresses and pointers. Because of potential portability problems it is therefore not likely that many programmers will have a great deal of use for this facility. However, one could take advantage of the fact that the elements of an array are stored contiguously to set up the addresses in the example above as follows:

  theStuffNumAdrs [1] := ADR (theStuff [1]);
  FOR count := 2 TO 13 (* set up addresses *)
    DO
      theStuffNumAdrs [count] := ADDADR (theStuffNumAdrs [count - 1], SIZE (Data))
    END;

This facility can also be useful when a particular machine is known to have certain specific memory set aside for special purposes, and it is desired to access that memory via pointers. Of course, such code is non-portable, as it makes assumptions about particular hardware.


Contents