Swap Two Pointers Using Double Pointers

Code

#include <stdio.h>

void swap_pointers(int **p1, int **p2) {
    // Your logic here
    int temp = **p1;
    **p1 = **p2;
    **p2 = temp;
}

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;
}

Solving Approach

  • Initial Setup:
    Two pointers ptr1a, and ptr2b.
  • Pass by Reference:
    Pass &ptr1 and &ptr2 (addresses of the pointers).
  • Inside Function:
    Use a temp pointer to swap *p1 and *p2 (the actual pointer addresses).
  • After Swap:
    Now ptr1 points to b, and ptr2 points to a.

 

 

Upvote
Downvote
Loading...

Input

10 20

Expected Output

20 10