54. Swap Two Pointers Using Double Pointers

Back To All Submissions
Previous Submission
Next Submission

Code

#include <stdio.h>
#include<stdint.h>

void swap_pointers(int **p1, int **p2) {
    //Step 1: Store the FIRST pointer in a temporary pointer variable
    int *temp = *p1;
    
    //Step 2: Make the FIRST pointer point to where the SECOND pointer is pointing
    *p1 = *p2;
    
    //Step 3: Make the SECOND pointer point to the temporary address
    *p2 = temp;

    //METHOD2:-
    // // Step 1: Disguise (*p1) and (*p2) as integers, XOR them, 
    // // and cast the result back into an (int *) pointer.
    // *p1 = (int *)((uintptr_t)*p1 ^ (uintptr_t)*p2);
    
    // // Step 2: Extract the original p1 address and store it in p2
    // *p2 = (int *)((uintptr_t)*p1 ^ (uintptr_t)*p2);
    
    // // Step 3: Extract the original p2 address and store it in p1
    // *p1 = (int *)((uintptr_t)*p1 ^ (uintptr_t)*p2);
}

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

 

 

 

Was this helpful?
Upvote
Downvote