While using pointers as arguments to a function, some care is required with the formal argument declarations within the function. Specifically, formal pointer arguments that must be preceded by asterisk.Function prototypes are written in the same manner. If a function declaration does not include variable names, the data type of each pointer argument must be followed by an asterisk.
The difference between ordinary arguments, which are passed by value, and pointer arguments, which are passed by reference is illustrated with the help of the following C program.
#include < stdio.h >
void funct1 (int u, int v); /*function prototype*/
void funct2 (int *pu, int *pv); /*function prototype*/
main()
{
int u = 1, v = 3;
printf("\nBefore calling funct1: u=%d v=%d", u, v);
funct1(u, v);
printf ("\nAfter calling funct1: u=%d v=%d", u, v);
printf ("\n\nBefore calling funct2: u=%d v=%d", u, v);
funct2(&u, &v);
printf ("\nAfter calling funct2: u=%d v=%d", u, v);
}
void funct1 (int u, int v)
{
u = 0;
v = 0;
printf ("\nwithin funct1: u=%d v=%d", u, v);
return;
}
void funct2 (int *pu, int *pv);
{
*pu = 0;
*pv = 0;
printf ("\nwithin funct2: *pu=%d *pv=%d", *pu, *pv);
return;
}
After execution of the program, the following output is generated;
Before calling funct1: u=1 v=3
within funct1: u=0 v=0
After calling funct1: u=1 v=3
Before calling funct2: u=1 v=3
within funct2: *pu=0 *pv=0
After calling funct2: u=0 v=0
Notice the values of u and v are unchanged within main after the call to funct1, though the values of these variables are changed within main after the call of funct2.
No comments:
Post a Comment