Thursday, November 5, 2009

12. Pointer Basics in Free Pascal

In Pascal there is what is called dynamic allocation of memory. We reserve space when we need it and dispose it off after using it. As each space in memory has an address, we grab the addresses depending upon our needs and dispose them when they are no longer needed.

Just like integer variables which store integers only, Pointer variables store only addresses in Pascal. Just like we use variables to manipulate values in them we manipulate pointer variables also with their values(addresses). Additionally with pointers, we can manipulate the values in spaces they point in the memory.

First we have to declare them just like anything else.
Ex: var p,q : ^integer;
the ^ before integer saying that p and q are pointers which store only addresses of integer spaces in memory.

Next we grab space in memory for pointers.
ex: new(p);
Give me new space to store integer and put that address in pointer p.

Next put an integer(3) in that space.
ex: p^ := 3;
p^ means put 3 in the space specified by the address in p.

Make pointer q also contain same address as p. ex: q := p;

Now get a new space for p. store 4 in it. ex: new(p); p^:= 4;

Display the contents of spaces pointed by p and q with writeln. ex: writeln('p = ', p^,' q = ',q^);

After we are done finished using spaces, we can dispose the spaces.
ex: dispose(p); dispose(q);

The following program describes all.

Program Program12;
(* Author: Rao S Lakkaraju *)
(* Pointer Basics *)
uses crt,graph;

var p,q : ^integer; { declares p and q as an integer pointer variables }

begin
clrscr;
new(p); { allot space for an integer for pointer p }
p^ := 3; { Dereference p to store integer 3 in that location }
q := p; { make pointer q pointing to the same location as p }
new(p); {allot another space for an integer for pointer p }
p^:= 4; (* store 4 in that location*)

{ Display the value in the location pointed by p and q }
writeln('p = ', p^,' q = ',q^);

dispose(p); { destroy pointer p and release memory }
dispose(q); (* destroy pointer q and release memory *)

writeln('My twelth Pascal program');
readln;
end.

Summary: Pointer variables are used for dynamic allocation of memory in Pascal. We can grab the memory we need, we use the space as we need and dispose it off after our use. Since we placed the memory addresses in pointers, pointers are our contacts to the memory spaces.

No comments:

Post a Comment