Next: , Previous: Parameters, Up: Programming



6.6 Pointer Arithmetics

GPC allows to increment, decrement, compare, and subtract pointers or to use them in for loops just like the C language.

GPC implements the address operator @ (a Borland Pascal extension).

     program PointerArithmeticDemo;
     var
       a: array [1 .. 7] of Char;
       p, q: ^Char;
       i: Integer;
     
     {$X+}  { We need extended syntax for pointer arithmetic }
     
     begin
       for p := @a[1] to @a[7] do
         p^ := 'x';
     
       p := @a[7];
       q := @a[3];
       while p > q do
         begin
           p^ := 'y';
           Dec (p)
         end;
     
       p := @a[7];
       q := @a[3];
       i := q - p;    { yields 4 }
     end.

Incrementing a pointer by one means to increment the address it contains by the size of the variable it is pointing to. For typeless pointers (Pointer), the address is incremented by one instead.

Similar things hold when decrementing a pointer.

Subtracting two pointers yields the number of variables pointed to between both pointers, i.e. the difference of the addresses divided by the size of the variables pointed to. The pointers must be of the same type.