Course Content
History of C Language
0/2
Basic Structure of C Program
0/1
Types of Errors
0/1
Language Fundamentals
0/1
Data Types and Modifiers
0/1
Programming with C Language
About Lesson

Pointers as Function Arguments

Like regular variables, pointer can also be passed as arguments to the function.  We know function accept arguments from their caller function at the time of invocation.  When local variables of caller functions are passed as arguments

, a copy of the values of actual arguments is passed to the calling function. Thus, any changes made to the variables inside the function will have no effect on variables used in the actual argument list.

However, when arguments are passed by reference (i.e. when a pointer is passed as an argument to a function), the address of a variable is passed. The contents of that address can be accessed freely, either in the called or calling function. Therefore, the function called by reference can

change the value of the variable used in the call.

/* Program that illustrates the difference between ordinary arguments, which are

passed by value, and pointer arguments, which are passed by reference */

# include

main()

{

int x = 10;

int y = 20;

void swapVal ( int, int ); /* function prototype */

void swapRef ( int *, int * ); /*function prototype*/

printf(“PASS BY VALUE METHOD\n”);

printf (“Before calling function swapVal x=%d y=%d”,x,y);

swapVal (x, y); /* copy of the arguments are passed */

printf (“\nAfter calling function swapVal x=%d y=%d”,x,y);

printf(“\n\nPASS BY REFERENCE METHOD”);

printf (“\nBefore calling function swapRef x=%d y=%d”,x,y);

swapRef (&x,&y); /*address of arguments are passed */

printf(“\nAfter calling function swapRef x=%d y=%d”,x,y);

}

/* Function using the pass by value method*/

void swapVal (int x, int y)

{

int temp;

temp = x;

x = y;

y = temp;

printf (“\nWithin function swapVal x=%d y=%d”,x,y);

return;

}

/*Function using the pass by reference method*/

void swapRef (int *px, int *py)

{

int temp;

temp = *px;

*px = *py;

*py = temp;

printf (“\nWithin function swapRef *px=%d *py=%d”,*px,*py);

return;

}

Pointer as Function Return value

A pointer can also be returned by a function as its return value to its caller.  Using this method a function can able change more than one values in the caller function, which is usually not possible in regular method.

/*Program that shows how a function returns a pointer */

# include

void main( )

{

float *a;

float *func( ); /* function prototype */

a = func( );

printf (“Address = %u”, a);

}

float *func( )

{

float r = 5.2;

return (&r);

}

 

You cannot copy content of this page