next up previous contents index
Next: Arrays Up: Pointers Previous: What is a pointer?   Contents   Index

Pointers and subroutines

One of the major uses of pointers arises in their connection with passing things into subroutines. Consider the following program.
#include <stdio.h>
void testit(int);
int main(void) {
  int i = 22;
  printf("Before testit(), i=%d\n", i);
  testit(i);
  printf("After testit(), i=%d\n", i);
  return 0;
}
void testit(int in) {
  printf("Within testit(), upon entering, in=%d\n", in);
  in = 11;
  printf("Within testit(), before leaving, in=%d\n", in);
}
This produces
Before testit(), i=22
Within testit(), upon entering, in=22
Within testit(), before leaving, in=11
After testit(), i=22
showing that altering the value of the argument passed into the subroutine in this way doesn't affect its value outside the routine (the variable is passed in by value). Consider now the following:
#include <stdio.h>
void testit(int*);
int main(void) {
  int i = 22;
  printf("Before testit(), i=%d\n", i);
  testit(&i);
  printf("After testit(), i=%d\n", i);
  return 0;
}
void testit(int *in) {
  printf("Within testit(), upon entering, in=%d\n", *in);
  *in = 11;
  printf("Within testit(), before leaving, in=%d\n", *in);
}
This produces
Before testit(), i=22
Within testit(), upon entering, in=22
Within testit(), before leaving, in=11
After testit(), i=11
showing that altering the value of a variable passed into a routine via a pointer does affect its value outside the routine.

This property of pointers can be often useful in designing subroutines. Consider the problem of finding the solutions to a quadratic equation ax2 + bx + c = 0, which are

x = $\displaystyle {\frac{{-b\pm\sqrt{b^2-4ac}}}{{2a}}}$

for real roots ( b2 -4ac > 0). We would want a routine to find these solutions to return the two roots, but this seems difficult at the level we are at, as up to now subroutines must return a basic data type (int, float, ...), and there is no fundamental data type for two floating point numbers. We can easily arrange this though through the use of pointers:
#include <stdio.h>
#include <math.h>
int quadratic(float, float, float, float *, float *);
int main(void) {
  float a=1.0, b=-6.0, c=8.0, r1, r2;
  if (quadratic(a, b, c, &r1, &r2)) {
    printf("The two roots are %f and %f\n", r1, r2);
  }
  else {
    printf("No real roots exist");
  }
  return 0;
}
int quadratic(float a, float b, float c, float *r1, float *r2) {
  float d;
  d = b*b-4.0*a*c;
  if (d > 0) {
    *r1 = ( -b + sqrt(d) ) / (2.0*a);
    *r2 = ( -b - sqrt(d) ) / (2.0*a);
    return 1;
  }
  else {
    return 0;
  }
}

next up previous contents index
Next: Arrays Up: Pointers Previous: What is a pointer?   Contents   Index