Pointers and References:

advertisement
Pointers and References:
Three words with closely related meanings: addresses, pointers, and references.
Addresses: we usually use this term when we are talking about hardware.
Addresses are the "names" for locations in the computer's memory (RAM). We
might speak of looking up, fetching, or storing into an address.
Pointers: these are the PL equivalent of addresses. Usually when we use pointers
it's because we're doing dynamic memory allocation, or because we want to get
efficiently from one part of a data structure to another. We speak of following a
pointer.
References: just another PL term for an address. We usually use it when we have
alternate names for the same memory location. Think of pass by reference. The
argument and the parameter are two names for the same location. When we use
the address stored in a reference variable, we speak of dereferencing it.
C++ distinguishes between lvalues and rvalues.
lvalues are the sorts of things that can go on the left of an assignment statement.
That is, they have to be addresses in the computer's memory.
rvalues are the sorts of things that can go on the right of an assignment statement.
That is, they are the sorts of things that can be put into a location in the computer's
memory, as well as the sort of thing we operate on. So examples of rvalues are all
the various kinds of data: numbers, characters, bools, etc. (but also pointers).
x = 1; // is OK because x is an lvalue and 1 is an rvalue.
x = y; // is OK, because x is an lvalue, and y can be converted to an rvalue by
fetching the contents of location y.
1 = x; // is not OK, because 1 is an rvalue and it cannot go on the left of =.
If I use &x on the RHS (right-hand side) of an assignment, it takes the lvalue x and
converts to a pointer rvalue, the pointer to (address of) x. Therefore I can assign it
to a pointer variable:
int x;
int* xp;
xp = &x;
I can even do limited arithmetic on it: &x + 1 is the location of the next integer in
memory after x. I can do comparisons:
if (xp == &x) ....
Why do we need pointers at all?
(1) Pointers represent relationships between objects. For example, an organization
chart shows who a employee's supervisor is, and who their subordinates are. In a
computer implementation we might have pointers representing the lines in an
organization chart.
(2) Pointers are efficient because they allow me direct access from one object to
another. All I have to do is follow the pointer. For example, to get from employees
to their supervisor, if all I had was the super's ID, I would have to search the data
base to find the employee with that ID, but if I have a pointer to the supervisor, I
can get to the supervisors object directly.
Download