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. |
|
If x is an array, when we call sort(x), the address of x[0] is passed to the function sort(). |
|
The function uses this address for manipulating the array elements. |
|
The address of a variable can be passed as an argument to a function in the normal fashion. |
|
When address is passed to a function , the parameters receiving the address should be pointers. |
|
The process of calling a function using pointer 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. |
|
Example: |
|
main() |
{ |
int x; |
x=20; |
change(&x); |
printf("%d\n",x); |
} |
change( int *p) |
{ |
*p=*p+10; |
} |
|
Explanation: When the function change() is called, the address of the variable x, not its value, is passed into the function change(). |
|
Inside change(), the value at which p points is incremented by 10 , and the changed value is then displayed in the main function. |
Other Recommended Posts on C programming
Post a Comment