You may already know that each variable resides in a memory location, and these memory locations have defined addresses. You can access them using the pointer's variable name, representing an address in memory.
Mytour's previous articles have covered the structure of a Pascal program as well as how to write functions in Pascal. Continuing the Pascal theme, this article delves deeper into the realm of pointers in Pascal.
Understanding Pointers in Pascal
Pointers in Pascal are dynamic variables with values representing the address of another variable, i.e., the direct address in memory. Similar to variables or constants, you need to declare a pointer before using it to store the address of any variable.
The general structure for declaring a pointer variable is:
type
ptr-identifier = ^base-variable-type;
In Pascal, the pointer type is defined by the up-arrow prefix symbol (^) followed by the base type. The base type determines the type of data elements. When a pointer variable is defined for a specific type, it can point to data items of that type. After defining the pointer type, we can use the var declaration to declare pointer variables.
var
p1, p2, ... : ptr-identifier;
Here's an example of a valid pointer declaration in Pascal:
Pointer variables access the memory region pointed to by a pointer using the caret symbol (^). For instance, the variable linked by the pointer rptr is accessed as rptr ^. It can be accessed like this:
rptr^ := 234.56;
Refer to the example below for a better understanding of pointers in Pascal:
After the above code is compiled and executed, it will return the following result:
Print Memory Addresses in Pascal
In Pascal, we can assign the address of a variable to a pointer variable using the address operator (@). Use this pointer to manipulate and access data items. However, suppose, for some reason, you need to use the memory address. In that case, you'll have to store it in a character-type variable.
The following example prints the memory address stored in the iptr pointer:
After compiling and executing the above code, it will return the following result:
NIL Pointer in Pascal
In cases where no precise address is assigned, you can assign the value NIL to a pointer variable. This operation is executed at the variable declaration time. Here is an example of a NIL pointer in Pascal:
After compiling and executing the above code, it will return the following result:
The ptr variable holds a value of 0
To check for a nil pointer, you can use the If statement below:
Pointers in Pascal
So, the Mytour article just introduced you to pointers in Pascal. Hopefully, after reading this article, you will gain more insights into Pascal. In the next Mytour article, we will further introduce you to record types in Pascal.