Tom Kelliher, CS18
Feb. 21, 1996
Pointer Variable:
A variable whose rvalue is a memory address.
Use *
in declaration:
int* pi; // pi is pointer to int char* pc, c; // pc is pointer to char; c is *just* a char float *pf, *pg; // pf, pg are pointers to float
Examples:
int i; int j; int* pi1; int* pi2; char* pc; pi1 = NULL; pc = NULL; pi2 = &i; // address-of operator --- yields lvalue pi1 = pi2; pc = &j; // wrong pc = (char*)&j; // ok but "weird" pi1 = pc; // wrong *pi2 = 5; // de-reference operator pi2 = &j; *pi2 = 16;
Remember: only variables have an lvalue
Example:
void f(void) { int i; // allocate storage for an int int j = 5; add(&i, j, 12); // pass i's lvalue } void add(int* sum, int a, int b) // sum is pointer to int { *sum = a + b; // sum holds i's address; therefore *sum refers to i }
Box trace?
Modify the following program so that pointer parameters are used rather than reference parameters:
#include <iostream.h> void factorial(int& f, int v); int main() { int val = -1; int fact; while (val < 0) { cout << "Enter a positive integer: "; cin >> val; } factorial(fact, val); cout << "The factorial of that is " << fact << endl; return 0; } void factorial(int& f, int v) { int partial; if (v <= 1) { f = 1; return; } else { factorial(partial, v - 1); f = v * partial; return; } }