Swap Two Pointers Using Double Pointers

Code

#include <stdio.h>

void swap_pointers(int **p1, int **p2) {
    int *temp =*p1;// pointer temp to point the address p1 deferenced by double pointer
    *p1 = *p2;//copying the address of p2 to address of p1 by deference the double pointer
    *p2 =temp;//then temp is the pointer which means the variable that sores the adress of p1 is copied to adress of p3

}

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

 

 

 

Upvote
Downvote
Loading...

Input

10 20

Expected Output

20 10