next up previous contents
Next: Acronyms Up: Getting Started in C++ Previous: Classes   Contents

Subsections

Pointers

Pointers are a very complex but incredibly powerful concept. They allow you to write elegant and efficient code, but also to introduce bugs which are very difficult to trace and fix.

Every byte which is stored in a computer's RAM has an address. Simplifying, you could say that the first byte in the RAM has the address 0, the second the address 1 and so on, as if all the RAM were a big array of bytes. (In reality, memory management a very complex subject; a good introduction would be longer than this entire tutorial. But for our needs this simplification is good enough.)

A pointer is exactly such an address. Giving it different adresses you can point it to different parts of memory; that's why it is called a pointer.

The value of a pointer is such an address; as it may be completely different on different machines and between different runs of the same program, it is completely useless and you should never use it. In fact, a pointer contains no data, in only point to data. The interesting part is what the pointer is pointing to, i.e. the data which resides at the address specified by the pointer. But let's look at some examples now.

Using Pointers

Declaring Pointers

In C++ (and also in C) pointers are a special type of variable, and must be declared just like any other variable. A pointer has the type ``pointer to something'', where something is any other data type. (You can even declare pointers to pointers, but more on that later).

For example, to declare a pointer to char you'd do something like this:

char* p;
The asterisk ``*'' means that p is a pointer; analogously a pointer to int is declared as follows:
int* p;

Notice that the space after the asterisk is optional; in fact, the following ways to declare a pointer are all equivalent, and only depend on the programmer's favourite style:

int* p;
int*p;
int *p;

There's a pitfall though. With ``normal'' (non-pointer) data types, you can declare more than one variable at once:

Assigning Pointers

Of course, to do anything useful with pointers you first need to assign them a value. You can either assign it a value from another pointer, or put the address of a real object into it:

// declare two pointers to int p and q
int* p, *q;
% todo

Dereferencing Pointers

The NULL Pointer

A Simple Example

Pointer Arithmetics

Examples

Exercises


next up previous contents
Next: Acronyms Up: Getting Started in C++ Previous: Classes   Contents
Aaron Isotton <aaron@isotton.com>
2003-02-24