February 4, 2002
Reading assignment:
Deitel and Deitel Chapter 5.5 - 5.9, 5.11
-or-
Wang 1.13, 4.2, 4.8-4.9, 4.11
Warm-up example:
Turn the following function from pass-by-reference to pass-by-pointer
void arithmetic(double, double, double &, double &); //prototype
int main()
{
double num1, num2, prod, quot;
num1 = 2.2;
num2 = 1.1;
arithmetic(num1, num2, prod, quot);
cout << "Product is " << prod << endl
<< "Quotient is " << quot << endl;
}
void arithmetic(double x1, double x2, double& p, double &q)
{
p = x1*x2;
q = x1/x2;
}
Pointer Arithmetic
- You can add and subtract integers from pointer values. When you add 1
to a pointer, it increments the pointer by the size of the type pointed to.
For example, on my machine, an int is 4 bytes. So if I have
int *iptr;
int i;
iptr = &i;
iptr++;
then iptr will be 4 larger after the last statement
- You can find out how many bytes it takes to store a type with
the sizeof operator. Use sizeof(type name) or sizeof(variable name).
- If two pointers point to elements in the same array, then they can
be subtracted. The result is the difference in index values of the array.
- Here's a little program that investigates this: pointer_arithmetic.cpp
"Const" and pointers
- We've learned already about constant variables and constant parameters
The situation is a wee big more complicated when pointers are involved
because const can refer to the value of the pointer or it can refer
to the value of the variable it points to.
- Each of the following possibilities apply to variables and to parameters
- These are ordered in increasing order of restriction. Use the most
restrictive you can because it's safer.
- Examples of each of these are given in 5.6 of Deitel and Deitel
1. nonconstant pointer, nonconstant data
The address that the pointer refers to can change,
and data at that location may be changed too
int *iptr
2. nonconstant pointer, constant data
The address that the pointer refers to can change,
but data at those locations may not change
const int *iptr
3. constant pointer, nonconstant data
pointer always points to the same location,
but the data at that location can be altered
int * const iptr
iptr MUST be initialized when defined
This is what an array actually is!
4. constant pointer, constant data
pointer always points to the same location,
and the data at that location can't be altered
const int * const iptr;
iptr MUST be initialized when defined
- Here's a little program demonstrating this: constptr.cpp
Arrays of pointers
- Arrays may contain pointers. One use is to store character arrays.
const char *numbers_in_english[5] = {"zero", "one", "two", "three", "four"};
Each of the words is itself a character array, which is really a pointer.