Puzzle P17

pointer value passed from one function to another

Passsing a Pointer value through two Functions

Of course, functions can call functions, and pass pointer values along. What does the following code write to the monitor?

#include <stdio.h>

void functionB( int *y )  
{
  printf("    *y=%d\n", *y );
  *y = 999;
  printf("    *y=%d\n", *y );
}

void functionA( int *x )  
{
  printf("  *x=%d\n", *x );
  functionB( x );          /* Note this!! */
  printf("  *x=%d\n", *x );
}

void main ( void )
{
  int a = 77;
  printf("a=%d\n", a );
  functionA( &a );
  printf("a=%d\n", a );
}

main() calls functionA with a pointer to a:

functionA( &a )

functionA then follows this pointer (now contained in its parameter x) and prints the contents of what it points to.

printf("  *x=%d\n", *x )

Then functionA calls functionB with the value in x:

functionB( x )

Bugs and more bugs!  Look carefully. The parameter x contains a pointer to a. This value is what we want to pass on, and the call functionB( x ) does this. The call

functionB( &x )

would pass a pointer to x (not what we want). The call

functionB( *x )

would pass the value in a , 77, which also would be wrong.

The call functionB(x) copies the value in x into the parameter y of the function. The function now has a pointer to a. When functionB executes

printf("    *y=%d\n", *y )

it follows y and prints out what it points to. Next the function executes

*y = 999

which follows the pointer in y and stores 999 in the variable a.



Previous Page        Answer         Next Page         Home