next up previous
Next: Function Arguments as Pointers Up: Getting More Out of Previous: Getting More Out of


We are going to use pointers quite a bit in this lesson, so let's see what they are and how to use them. When we declare a variable, as in

    float x;

the compiler sets aside memory for the variable x. Single-precision values (type float) take four bytes of memory per number. Each byte of memory has an address (a number). If your computer has 1 Gigabyte of memory, that address could be as large as one billion. We don't usually need to know the exact number, but it is often useful to refer to the address of x. The compiler gives us the address if we put an ampersand & in front of the variable name. So &x is the address of x. We can declare variables that contain addresses. Such variables are called pointers. Their datatypes get an extra asterisk *. So pointers to values of type float have the datatype float *. Here is an example that declares that xp is a pointer to a float:

    float * xp;

It is OK to omit one of the spaces before or after the *, as in

    float *xp;

Pointers take only address values. Here is how we assign the address of x to xp:

    xp = &x;

Every datatype has its special pointer type, which you get by putting an asterisk after the base datatype name. The compiler is very particular about not mixing pointers to different types. The assignment above is legal because x has type float, the ampersand converts it into the address of a float type, and xp is of type ``pointer to a float''. If x had been of type double this would have been an illegal assignment. Sometimes we have a pointer variable, and we want to get the value it points to. Continuing with the example above, suppose we know only xp but we want to get x. This is done by putting an asterisk * in front of the pointer name. So assuming that xp is the address of x, if we then do

    float y;
    y = *xp;

then y is assigned the value of x. So the asterisk * operation undoes the & operation:

    y = *(&x);

is the same as y = x. It is sometimes said that the asterisk deferences the pointer, but the terminology is confusing, because we use the term ``reference'' for something quite different in C++.
next up previous
Next: Function Arguments as Pointers Up: Getting More Out of Previous: Getting More Out of
Carleton DeTar 2009-09-23