Advertise here.

Tuesday 28 August 2012

Pascal Programming Lesson #13 - Pointers


A pointer is a type of variable that stores a memory address. Because it stores a memory address it is said to be pointing to it. There are 2 types of pointers which are typed and untyped. A typed pointer points to a variable such as an integer. An untyped pointer can point to any type of variable.

Declaring and using typed pointers

When you declare a typed pointer you must put a ^ in front of the variable type which you want it to point to. Here is an example of how to declare a pointer to an integer:

program Pointers;

var
   p: ^integer;

begin
end.

The @ sign can be used in front of a variable to get its memory address. This memory address can then be stored in a pointer because pointers store memory addresses. Here is an example of how to store the memory address of an integer in a pointer to an integer:

program Pointers;

var
   i: integer;
   p: ^integer;

begin
   p := @i;
end.

If you want to change the value stored at the memory address pointed at by a pointer you must first dereference the pointer variable using a ^ after the pointer name. Here is an example of how to change the value of an integer from 1 to 2 using a pointer:

program Pointers;

var
   i: integer;
   p: ^integer;

begin
   i := 1;
   p := @i;
   p^ := 2;
   writeln(i);
end.

You can allocate new memory to a typed pointer by using the new command. The new command has one parameter which is a pointer. The new command gets the memory that is the size of the variable type of the pointer and then sets the pointer to point to the memory address of it. When you are finished using the pointer you must use the dispose command to free the memory that was allocated to the pointer. Here is an example:

program Pointers;

var
   p: ^integer;

begin
   new(p);
   p^ := 3;
   writeln(p^);
   dispose(p);
end.

Declaring and using untyped pointers

When you declare an untyped pointer you must use the variable type called pointer.

program Pointers;

var
   p: pointer;

begin
end.

When you allocate memory to an untyped pointer you must use the getmem command instead of the newcommand and you must use freemem instead of disposegetmem and freemem each have a second parameter which is the size in bytes of the amount of memory which must be allocated to the pointer. You can either use a number for the size or you can use the sizeof function to get the size of a specific variable type.

program Pointers;

var
   p: pointer;

begin
   getmem(p,sizeof(integer));
   freemem(p,sizeof(integer));
end.

0 comments:

Post a Comment