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.

1. What Are Pointers?

A pointer is a dynamic variable whose value is the address of another variable i.e. direct address of the memory location. Like any variable or constant, you must declare a pointer before you can use it to store any variable address. The general form of a pointer variable declaration is:

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.

When the above code is compiled and executed, it produces following result:

Number is: 100
iptr points to a value: 100
Number is: 200
iptr points to a value: 200

2. Printing a Memory Address in Pascal

In Pascal, we can assign the address of a variable to a pointer variable using the address operator (@). We use this pointer to manipulate and access the data item. However, if for some reason, we need to work with the memory address itself, we need to store it in a word type variable.

Let us extend the above example to print the memory address stored in the pointer iptr:

When the above code is compiled and executed, it produces following result:

Number is: 100
iptr points to a value: 100
Number is: 200
iptr points to a value: 200
36864

3. NILL Pointers

It is always a good practice to assign a NILL 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 NILL points to nowhere. Consider the following program: