CSC 161 Schedule Readings Labs & Projects Homework Deadlines Resources

Functions and Pointer Parameters

Introduction

Today we reveal an important aspect of memory and parameter passing that has been mostly abstracted in your programming work so far. Namely, we show how to identify the memory address of a particular variable, which can be used as a function parameter to modify the variable's value outside that procedure.

Textbook Reading

Begin with a reading from your textbook:

Summary of Value and Address Parameters

The lab on functions and parameters considered two basic types of function parameters:

Suppose variable number is declared as follows in a main function:

double number = 123.45;

Value Parameter Passage

In the following code, execution of the valueAsParameter function creates a new variable valueParameter, and the call of the valueAsParameter copies a value to valueParameter.

As an example, consider the following code:

void valueAsParameter(double valueParameter)
{
   printf("value of valueParameter at start of valueAsParameter: %lf\n",
          valueParameter);

   valueParameter = 543.21;

   printf("value of valueParameter at end of valueAsParameter: %lf\n",
          valueParameter);
}

int main ()
{
   double number = 123.45;
   valueAsParameter(number);
   printf ("value of number after valueAsParameter completed:  %lf\n", number);
}

When this code is executed,

Altogether, value parameter passage copies a value to the new parameter, work in the function works with the copied value, and changes to the new parameter do not affect the original variable (in main).

Passing Addresses as Parameters

In the following code, execution of the addressAsParameter function stores the address (not the value) of the original variable. Using the address as the parameter, changes at the stored address refer back to the main variable.

As an example, consider the following code:

void addressAsParameter (double* addressParameter)
{
   printf("value of valueParameter at start of addressAsParameter: %lf\n",
          *addressParameter);

   *addressParameter = 543.21;

   printf("value of valueParameter at end of addressAsParameter: %lf\n", 
          *addressParameter);
}

int main ()
{
   double number = 123.45;
   addressAsParameter (&number);
   printf ("value of number after addressAsParameter completed:  %lf\n",
	   number);
}

When this code is executed,