35. Swap Two Pointers Using Double Pointers

#include <stdio.h>

// Function to swap two pointers using double pointers
void swap_pointers(int **p1, int **p2) {
    int *temp = *p1; // Store address pointed by p1
    *p1 = *p2;       // p1 now points to what p2 was pointing
    *p2 = temp;      // p2 now points to what p1 was pointing
}

int main() {
    int a, b;
    scanf("%d %d", &a, &b);

    int *p1 = &a;
    int *p2 = &b;

    swap_pointers(&p1, &p2);

    printf("%d %d", *p1, *p2);

    return 0;
}
  • We receive the addresses of the pointers themselves (int **p1, int **p2).
  • Use a temporary pointer to store one address.
  • Swap the addresses: *p1 gets *p2, *p2 gets temp.
  • After swapping, dereferencing p1 and p2 gives swapped values.

 

Loading...

Input

10 20

Expected Output

20 10