Reference and Pointer Function Parameters

Tom Kelliher, CS18

Feb. 21, 1996

Pointer Variables and Parameters

Pointer Variable:

A variable whose rvalue is a memory address.

Declaring a Pointer Variable

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

Initializing, De-referencing a Pointer Variable

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

Pointer Parameters

  1. Actual parameter must be an lvalue
  2. Formal parameter must be pointer to appropriate type
  3. Within function body, formal parameter must be dereferenced

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;
   }
}



Thomas P. Kelliher
Tue Feb 20 09:24:54 EST 1996
Tom Kelliher