Sunday, November 16, 2008

Pointers and Functions

POINTERS AND FUNCTIONS

When an array is passed to a function as an argument, only the address of the first element of the array is passed, but not the actual values of the array elements. The function uses this address for manipulating the array elements. Similarly, we can pass the address of a variable as an argument to a function in the normal fashion.


When we pass addresses to a function, the parameters receiving the addresses should be pointers. The process of calling function using pointers to pass the address of variable is known as call by reference. The function which is called by reference can change the value of the variable used in the call.
eg.

main ( )

{

int X ;

X = 40 ;

change ( & X ) ;

printf ( “ %d”, X ) ;

{

change ( int * P )

{

* P = * P + 10 ;

}

When the function change is called, the address of the variable X, not its value, is passed into the function change ( ). Inside change ( ), the variable P is declared as a pointer and therefore P is the address of the variable X. The statement,
* P = * P + 10 ; means add 10 to the value stored at address P.

Since P represents the address of X, the value of X is changed from 50. Therefore, the output of the program will be 50 not 40.

Thus, call by reference provides a mechanism by which the function can change the stored values in the calling function.

No comments: