You've already seen ARRAY and RECORD in Pascal. This time we'll look at using the POINTER data type.
What Is a Pointer?
Pointers are a feature you mostly find in older programming languages. A pointer gets you the address of a variable in memory.
Every variable you create in Pascal ends up stored in the computer's RAM. That storage doesn't go by variable name, though, it uses an address built out of binary numbers.
Inside RAM itself there are also memory locations called the stack and the heap. We'll probably cover those another time, because it can get long, hehe...
So what are pointers good for?
Pointers are useful in complex programs for dynamic memory allocation and for using memory efficiently. Since we're still on the basics, for now we'll just use a pointer as a reference to a variable.
Declaring a Pointer in Pascal
To use a pointer you have to declare it as a data type. A variable of pointer type can only hold the address of another variable.
You declare a pointer by putting a caret (^) in front of the data type you're declaring.
var
pointer-name: ^data-type;
For example:
var
strptr: ^string; // a pointer to the string data type
intptr: ^integer; // a pointer to the integer data type
Getting a Variable's Address
Since a pointer can only be filled with a variable's address, you have to know the address of the variable you want to put in it.
To get the address of a variable you use the @ sign before the variable name.
Let's go straight to a simple program.
program Pointer;
uses crt;
var
strptr: ^string; // create a pointer with the string type
kata: string;
begin
clrscr;
strptr := @kata; // strptr holds the address of variable kata
writeln(kata);
readln;
end.
Yep, if you run it nothing shows up, but the variable strptr now holds the address of the variable kata.
Next we can change the variable kata indirectly through the pointer. Let's keep going..
Accessing a Pointer's Value
To change the value of kata through the pointer, we access its value with the caret (^) written after the variable name.
program Pointer;
uses crt;
var
strptr: ^string; // create a pointer with the string type
kata: string;
begin
clrscr;
strptr := @kata; // strptr holds the address of variable kata
strptr^ := 'Belajar pointer di invasikode'; // access the pointer's value
writeln(kata);
readln;
end.
If you run it, the output will come out something like this:
Belajar pointer di invasikode
That program never touches the variable kata directly. We use the pointer as a reference to kata and change it indirectly.
You can do this with every data type, including RECORD, SUBRANGE, and ENUM.
Wrapping Up
Right now pointers probably look unimportant. Just wait until we get to FUNCTION and PROCEDURE, where a pointer becomes very handy for manipulating data, with the same concept of course.
That's all for this tutorial, hope it helps :D
Next we'll look at the concept of procedural programming in Pascal