Jan 30, 2002
Reading assignment:
Deitel and Deitel Chapter 5.1-5.4
-or-
Wang Section 4.1-4.2 (these sections are lean on details)
Pointer variables
- It is with the use of pointers that we can achieve dynamic memory
allocation.
- A pointer variable is in some ways just like other variables, it
has its own slot in memory where a number is stored. But it's different
in a way, because the number in the slot gives a memory location for
another variable that holds the value you really care about.
- The other types of variables we've studied give you direct access to
a number, while a pointer gives you indirect access. It gives indirect
access because it tells you where to look to get the number.
- Here are some examples of definitions of pointer variables:
int *iptr; // the variable called iptr is a pointer to an int
double *double_ptr; // double_ptr is a pointer to a double
string *w; // w is a pointer to a string object
int *ip, jp; // careful! ip is a pointer to an integer,
// but jp lacks the *, so it is just an int!
- To make the connection between a pointer and the value of the variable
it points to, we need two operators, the address-of operator
and the indirection (or dereferencing) operator
- Since a pointer is an address, we need a way to get the address of
the variable that the pointer points to. The "address-of" operator &
does this. Don't confuse the address-of operator & with the same
symbol used for references - the compiler distinguishes them by context.
An example of a use of this is
int i=47;
int *iptr;
iptr = &i;
iptr now contains the memory address where i is stored.
We say "iptr points to i".
- If iptr points to i, we need a way to look at the value of i by using
iptr. The indirection operator * does this. An example:
int j;
j = *iptr;
cout << *iptr;
Warning: if iptr contains a bogus address, then executing a statement
that includes *iptr will cause the program to crash, because you're
trying to access the data at a bogus location.
- Here's a program demonstrating pointers:
pointer.cpp
Using pointer variables for function parameters
- This achieves an effect similar to call-by-reference.
- You can make a function take a pointer as an argument. This is a way
for the function to get its hands on the caller's variables. This
allows us to avoid copying the variable, and allows the function to
modify the caller's variable(s)
- The prototype and definition should have, for example, a float *
as a parameter. The caller then would have a float variable,
say it's called fl. It then passes &fl to the function.
- Here's a program that shows you how to do this:
pointerparam.cpp