next up previous
Next: Variable Scope Up: Getting More Out of Previous: Pointers

Function Arguments as Pointers

As we have noted pointers take address values. In C we use pointers as arguments in subprogram calls to get back output values. In the next subsection we show how to do it more simply in C++ with reference variables. If the subprogram was coded in Fortran, and a great many useful scientific subroutine libraries are, in most cases you must pass all arguments as pointers. So it is important to learn how to use them. Here is an example. In place of the two separate functions, we define the double-duty subprogram with pointer arguments this way:

// The definition of the subprogram
void f_and_df(double x, double *fp, double *dfdxp){
   *fp = 4*x - cos(x);         // the * dereferences the pointer
   *dfdxp = 4 + sin(x);
}

In the main program we call the subprogram this way:

int main(){
     double x, f, dfdx;
     ...
     // The calling statement:
     f_and_df(x, &f, &dfdx);  // Arguments 2 and 3 are pointers to doubles
     pnew = p - f/dfdx;
     ...
}

There are a several new features here, so let's take them one at a time:
next up previous
Next: Variable Scope Up: Getting More Out of Previous: Pointers
Carleton DeTar 2009-09-23