Pointer

From SwinBrain

A pointer is a data abstraction used to refer to values at other locations in memory.

Illustration of a Pointer with Pascal syntax.


Care must be taken when working with Pointers, especially when using dynamically allocated memory. The Memory Management article covers some different approaches to help ensure you manage dynamically allocated memory correctly.

Basic Pointer Operations

Operation C Example Pascal Example Description
Declare a pointer int *p; p: ^Integer Declare a pointer variable p, in this case the pointer points to an integer value.
int[] p; Arrays in C are pointers to the first element in the array.
Point to a value p = &x; p := @x; Create a pointer that refers to the address of another value.
In this case the resulting pointer will point to the value in variable x.
Dynamically Allocate Memory p = (int *) malloc(sizeof(int)); New(p); Allocate space on the heap, sufficient to store an integer in this case,
and set p to point to this newly allocated space.
You must ensure the space is freed when you are finished!
De-reference pointer *p p^ Follows the pointer to access the value pointed to.
Can be used to read or write to the accessed value.
p->field This version of a de-reference is used to access field members
in cases where p points to a structure.
Free space free(p); Dispose(p); Frees space allocated dynamically and referred to by the pointer, p in this case.
This memory should no longer be accessed by the program.
Pointing to nothing p = NULL; p = nil; This allows you to point a pointer to nothing.
Useful after having freed the allocated memory to ensure
you don't accidently access it at a later point.


Pointer Manipulation

Languages using pointers often allow you to manipulate where the pointer is pointing. In all of these cases the language will move the pointer based on the size of the data type it is pointing to. For example, p++ in C will move the pointer forward 4 bytes (32bits) if it is pointing to a 32bit integer value. Similarly in Pascal Dec(p) will move the pointer back 8 bytes (64bits) if it is pointing to a 64bit floating point value.

Operation C Example Pascal Example Description
Pointing to n'th value p + n p + n Shifts the pointer the size it is pointing to forward through memory.
This will result in a pointer that points to the n'th value from p.
Pointing back n values p - n p - n Shifts the pointer the size it is pointing to backward through memory.
This will result in a pointer that points to the n'th value back from p.
Move pointer forward p++; Inc(p); Effectively p = p + 1, moves the pointer to point to the next value in memory.
Move pointer backward p--; Dec(p); Effectively p = p - 1, moves the pointer to point to the previous value in memory.


Warning: Take care with pointer manipulation. The language is not likely to be protecting you from doing stupid things when you use these operators.

[edit]Links: Topic Brains
Return to Swin Brain