What does the following code write to the monitor?
#include <stdio.h>
void newFunction( int *p )
{
printf(" *p=%d\n", *p );
*p = 123;
printf(" *p=%d\n", *p );
}
void main ( void )
{
int a = 77 ;
printf("a=%d\n", a ) ;
newFunction( &a ) ;
printf("a=%d\n", a ) ;
system("pause") ;
}
Call by value is used in this example, also.
However, the parameter p
of newFunction()
requires a value that is of type pointer to int:
int *p
main() supplies such a value
in the function call newFunction( &a ).
The expression &a evaluates
to the address of a.
(Often this is called a pointer to a.)
When newFunction() is called, the address
of a is copied into the parameter p. Now newFunction()
can access a by following the pointer. The statement
printf(" *p=%d\n", *p );
follows the pointer in p to get a value (which is then printed).
The statement
*p = 123;
follows the pointer in p to the location in which to store the
value of the expression on the right of the =. This location
is the variable a, which is then changed.