Program 54) Write a function using pointers to exchange the values in tw2o location in the memory.
This program shows how the content of two locations can be exchanged using their address locations. The function exchange ( ) recieves the addresses of the variables x and y exchanges their contents.
PROGRAM
void exchange (int *, int *) ; /* prototype */
main ( )
{
int x, y ;
x = 100 ;
y = 200 ;
printf ("Before exchange : x = %d y = %d\n\n", x, y) ;
exchange (&x, &y) ; /* call */
printf ("After exchange : x = %d y = %d\n\n", x, y) ;
}
exchange (int *a, int *b)
{
int t ; /* Assign the value at address a to t */
t = *a ; /* put b into a */
*a = *b ; /* put t into b */
}
Output: Before exchange : x = 100 y = 200
After exchange : x = 200 y = 100
You may note the following points:
1. The function parameters are declared as pointers.
2. The dereferenced pointers are used in the function
body.
3. When the function is called, the addresses are passed
as actual arguements.
No comments:
Post a Comment