- - * - WhiteUnicorn - * - -




* #WhiteUnicorn/ StartPage/ Documentation/DelphiFAQ >


2858:How to do pointer arithmetic in Delphi.

KEYWORDS: pointer arithmetic AREA: General

Q:  How do I do pointer arithmetic in Delphi?

A:  First a brief explanation of pointer arithmetic.  When you
are dealing with dynamic memory locations and all you have is a
pointer to where it all begins, you want to have the ability to
traverse that line of memory to be able to perform whatever
functions you have in mind for that data.  This can be
accomplished by changing the place in memory where the pointer
points.  This is called pointer arithmetic.

The main idea that must be kept in mind when doing your pointer
arithmetic is that you must increment the pointer's value by
the correct amount.  (The correct amount is determined by the
size of the object receiving the pointer.  e.g.  char = 1 byte;
integer = 2 bytes; double = 8 bytes;  etc.)  The Inc() and
Dec() functions will alter the amount by the correct amount.
(The compiler knows what the correct size is.)

For an example of the practical application of pointer
arithmetic, download the BreakApart() TI2905.

If you are doing dynamic memory allocation, it is done like this:

uses WinCRT;

procedure TForm1.Button1Click(Sender: TObject);
var
  MyArray: array[0..30] of char;
  b: ^char;
  i: integer;
begin
  StrCopy(MyArray, 'Lloyd is the greatest!'); {get something to point to}
  b := @MyArray; { assign the pointer to the memory location }
  for i := StrLen(MyArray) downto 0 do
  begin
    write(b^);   { write out the char at the current pointer location. }
    inc(b);      { point to the next byte in memory }
  end;
end;

The following code demonstrates that the Inc() and Dec() functions
will increment or decrement accordingly by size of the type the pointer
points to:

var
  P1, P2 : ^LongInt;
  L : LongInt;
begin
  P1 := @L; { assign both pointers to the same place }
  P2 := @L;
  Inc(P2);  { Increment one }

{ Here we get the difference between the offset values of the
two pointers.  Since we originally pointed to the same place in
memory, the result will tell us how much of a change occured
when we called Inc(). }

  L := Ofs(P2^) - Ofs(P1^); { L = 4; i.e. sizeof(longInt) }
end;

You can change the type to which P1 and P2 point to something other than a
longint to see that the change is always the correct value (SizeOf(P1^)).

        TI



* #WhiteUnicorn/ StartPage/ Documentation/DelphiFAQ >



- - * - Anastasija aka WhiteUnicorn - * - - LJLiveJournal
PFPhotoFile