C Programming – Swap function using Pointers , pass by address
To learn basics of pointer & pointer arithmetic concepts, refer tutorial Array and Pointers Arithmetic in C Programming – Examples
Swap is function to exchange or interchange the values of two variables. This function interchange the value of two variable using temporary variable.
void swap(int *p,int *q)
printf("\nBefore swap value of x= %d value of y is %d\n",x,y);
swap(&x,&y); //pass by address
printf("\nAfter swap value of x= %d value of y is %d\n",x,y);
In this code,
Step-1: In main function, x and y are integer type variables are initialized to 100 and 200 respectively,
Step-2: display the values of x and y before swap function call.
Step-3: swap function is called, address of x and y are send as parameter.
Step-4: In swap function, these addresses are placed in pointer variable p and q, i.e pointer variable p holds the address of x variable and pointer variable q holds the address of y variable.
Step-5: In swap, t is temporary variable,
t= *p; *p gives the value stored at variable x, which is 100 and assigns to variable t.
*p=*q; *q gives the value stored at variable y, which is 200 and assigns to
*p , i.e as value for variable x becomes 200
*q=t; assign the value of t to variable , which is 100 to
*q , i,e as value of for y variable becomes 100
step-6: In main function, display the values of x and y again, which is interchanged.