Ad

Swap Variables That Pointers Point In

This function replaces values ​​of two integer variables using two pointers. I need to make function which will make p1 point to b and p2 point to a.

#include <stdio.h>
void swap(int *p1, int *p2) {
    int temp = *p1;
    *p1 = *p2;
    *p2 = temp;
}
int main() {
    int a, b;
    scanf("%d %d", &a, &b);
    swap(&a, &b);
    printf("%d, %d", a, b);
    return 0;
}

How could I modify this to make p1 point on b, and p2 point on a?

Ad

Answer

It seems you mean something like the following

#include <stdio.h>
void swap(int **p1, int **p2) {
    int *temp = *p1;
    *p1 = *p2;
    *p2 = temp;
}
int main() {
    int a, b;
    scanf("%d %d", &a, &b);
    
    int *p1 = &a;
    int *p2 = &b;

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

    swap(&p1, &p2);

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

    return 0;
}
Ad
source: stackoverflow.com
Ad