How to declare pointers in Pascal
Pointers are variables that store the memory address of another variable. In Pascal, a pointer is declared as:
_variableName_ = ^_addressedType_;
_variableName_: The variable name identifying the pointer._addressedType_: The data type of the variable whose memory address is stored in_variableName_.
Assigning a memory address to a pointer
To assign a memory address of a variable to a pointer, use the @ operator or addr() function to reference the variable as shown below:
_ptr_ := @_variable_;
Or:
_ptr_ := addr(_variable_);
@_variable_ stores the memory location of _variable_ in _ptr_.
Dereferencing a pointer
Dereferencing a pointer means accessing the data pointed by the pointer. To dereference a pointer in Pascal, use the ^ operator as shown below:
_pointedData_ := _pointer_^;
Examples
Example 1
Consider the code snippet below, which demonstrates the declaration of pointers:
program pointerExample1;{$TYPEDADDRESS ON}varnum1: Integer = 10;ptrnum: ^Integer;beginptrnum := @num1;writeln(ptrnum^);end.
Explanation
A pointer ptrnum is declared in line 5. ptrnum is pointed to a variable num1 that is declared in line 4 using the @ operator. Dereferencing ptrnum in line 8 prints the same value stored in num1 as the pointer pointed to num1.
Example 2
Consider another example that uses addr() to assign a memory address to the pointer:
program pointerExample2;{$TYPEDADDRESS ON}varnum1: Integer = 10;ptrnum: ^Integer;beginptrnum := nil;ptrnum := addr(num1);writeln(ptrnum^);end.
Explanation
A pointer ptrnum is declared in line 5. ptrnum is pointed to a variable num1 that is declared in line 4 using addr(). Dereferencing ptrnum in line 8 prints the same value stored in num1 as the pointer pointed to num1.
Free Resources