#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=22showing 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=11showing 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
#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; } }