Pointers

The Throb class described in the previous section used pointers to the three instances of the class Throb.

A pointer is declared by putting an asterisk in front of the variable name:

Throb *a, *b, *c;

You can have pointers to integers, chars, floats, doubles, structs, or anything that has a memory address. A pointer is simply a number that says where in memory some object is.

To use a pointer to a simple type, you just put an asterisk in front of the variable name:

int values[14];
int *pointer_to_value = &values[4];
*pointer_to_value = 19;

The ampersand gets the address of the object, so we can store it in the pointer.

If the object is a struct or a class, we use the arrow operator to reference things inside the structure:

a->change();

That says to call the change() method of the Throb object that the pointer 'a' points to.

Pointers can be very useful in large complicated programs, but are not often seen in programs that run on tiny microcontrollers.

We can get the address of a function and use a pointer to call that function. This can be handy when we want to have an array of things that the program can do, and select a function from the array. We could make our Rover dance randomly:

typedef void (*function)( void );

function list[] =
{
  forward,
  reverse,
  stop,
  forward_right,
  forward_left,
  spin_right,
  spin_left,
  reverse_right,
  reverse_left
};

void
dance( void )
{
  for( ;; )
    (*list[random(9)])();
}

That says to define a type (that's the typedef operator) called function that is a pointer to a function that takes no arguments and returns no value. Then it uses that type to declare a list of addresses of functions (the motion functions we already have in the Rover program). Then the dance() function picks a random number from 0 to 9, and uses that as the index to pick a function to call.

Again, this kind of thing is rarely done on tiny computers.