Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

pascal

How to declare pointers in Pascal

Kainat Asif

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}
var 
  num1: Integer = 10;
  ptrnum: ^Integer;
begin
  ptrnum := @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}
var 
  num1: Integer = 10;
  ptrnum: ^Integer;
begin
  ptrnum := 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.

RELATED TAGS

pascal

CONTRIBUTOR

Kainat Asif
Copyright ©2022 Educative, Inc. All rights reserved
RELATED COURSES

View all Courses

Keep Exploring