All submissions

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

/*
Questions:
1. What exactly needs to be swapped? -> addresses not the values
2. constraints (valid pointers)
3. Expected behaviors
4. Edge cases


Plan:
- two int vars, pointers to these vars and two double ptrs to these pointers
- output : swapped pointers
- use a third var to swap the pointer to hold one address
- deref the double pointers

*/

 

 

Loading...

Input

10 20

Expected Output

20 10