Pointers In Pascal
Pointers In Pascal
Pointers in Pascal are easy and fun to learn. Some Pascal programming tasks are performed more
easily with pointers, and other tasks, such as dynamic memory allocation, cannot be performed
without using pointers. So it becomes necessary to learn pointers to become a perfect Pascal
programmer. Let's start learning them in simple and easy steps.
As you know, every variable is a memory location and every memory location has its address
defined which can be accessed using the name of the pointer variable, which denotes an address
in memory.
type
ptr-identifier = ^base-variable-type;
The pointer type is defined by prefixing the up-arrow of caret symbol ^ with the base type. The
base-type defines the types of the data items. Once a pointer variable is defined to be of certain
type, it can point data items of that type only. Once a pointer type has been defined, we can use
the var declaration to declare pointer variables.
var
p1, p2, ... : ptr-identifier;
type
Rptr = ^real;
Cptr = ^char;
Bptr = ^ Boolean;
Aptr = ^array[1..5] of real;
date-ptr = ^ date;
Date = record
Day: 1..31;
Month: 1..12;
Year: 1900..3000;
End;
var
a, b : Rptr;
d: date-ptr;
The pointer variables are dereferenced by using the same caret symbol ^ . For example, the
associated variable referred by a pointer rptr, is rptr^. It can be accessed as −
rptr^ := 234.56;
program exPointers;
var
number: integer;
iptr: ^integer;
begin
number := 100;
writeln('Number is: ', number);
iptr := @number;
writeln('iptr points to a value: ', iptr^);
iptr^ := 200;
writeln('Number is: ', number);
writeln('iptr points to a value: ', iptr^);
end.
When the above code is compiled and executed, it produces the following result −
Let us extend the above example to print the memory address stored in the pointer iptr −
program exPointers;
var
number: integer;
iptr: ^integer;
y: ^word;
begin
number := 100;
writeln('Number is: ', number);
iptr := @number;
writeln('iptr points to a value: ', iptr^);
iptr^ := 200;
writeln('Number is: ', number);
writeln('iptr points to a value: ', iptr^);
y := addr(iptr);
writeln(y^);
end.
When the above code is compiled and executed, it produces the following result −
NIL Pointers
It is always a good practice to assign a NIL value to a pointer variable in case you do not have
exact address to be assigned. This is done at the time of variable declaration. A pointer that is
assigned NIL points to nowhere. Consider the following program −
program exPointers;
var
number: integer;
iptr: ^integer;
y: ^word;
begin
iptr := nil;
y := addr(iptr);
writeln('the vaule of iptr is ', y^);
end.
When the above code is compiled and executed, it produces the following result −
Concept Description
Loading [MathJax]/jax/output/HTML-CSS/jax.js