devxlogo

Swapping Two Pointers (Using Pointers to Pointers)

Swapping Two Pointers (Using Pointers to Pointers)

Sometimes come across a situation where you need to swap two variables. Below is the code that will let you swap two pointers. Say that p and q point to x and y respectively. After swapping them, p and q would point to variables y and x respectively. However, the address of x and y will remain unchanged.

 void swap(int **p1, int **p2){	int *temp;	temp = *p1;	*p1 = *p2;	*p2 = temp;}//Calling syntax is swap(&p,&q);

devx-admin

Share the Post: