Pascal Programming/Pointers
From Wikibooks, the open-content textbooks collection
Back to Pascal Programming
Pointers are pointers or addresses to specific variables in the memory. Pointers allow the developer to make an alias or referencing of a specific variable. Professionally, Pointers are being used for lists as they require less memory although they are more complicated.
A sample pointer app:
program Pointers; var number : integer; { ^ before the type shows that it's a pointer } numbers_pointer : ^integer; begin { Set to 5 } number := 5; { Output } writeln('Number is ', number); { Assign the number's address, which is @number to numbers_pointer } numbers_pointer := @number; { To access the pointer's address, you've got to add a ^ after the pointer variable's name: } numbers_pointer^ := 8; writeln('Pointed Content is: ', numbers_pointer^); { 8 } writeln('Number is: ', number); { Should be 8 } end.
Pointers are introduced as lists, explained above. Simply, you've got to point to the next or the previous record.
Note that there are three ways pointers are notated:
- the "@" indicates the memory address of another type; it is a common way of initializing a pointer. - when "^" is placed before a name, you are asking for a pointer for a particular type, like a pointer to an integer or a char. Alternately you can use the generic "Pointer" type if you wish to use a pointer to reference many kinds of objects. - when "^" is placed after a name, you are asking for a dereference - for an existing pointer to return the variable it's referencing. So if you have a variable you wish to change, but have only a pointer to access it from, you use "variable^" to obtain the value.
Pascal pointers are often notated as "Pvar" where "var" or "Tvar" is the original.
One significant difference between C and Pascal programming is that C requires the use of pointers in more cases. When you call a function in C, there is no "var" keyword to indicate pass-by-reference; instead, C expects you to call the function with a pointer to the variable you want changed, and then dereference the pointer inside the function. Although the functionality is nearly the same, Pascal was originally designed to use pass-by-reference for subroutines, and pointers for complex data structures; later implementations added more generalized functionality for pointers.