2

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?

Vlad from Moscow
  • 301,070
  • 26
  • 186
  • 335
  • Does this answer your question? [Changing address contained by pointer using function](https://stackoverflow.com/questions/13431108/changing-address-contained-by-pointer-using-function) – kaylum Feb 03 '22 at 21:25
  • 1
    I think I know what you mean, but your code does not match what you describe. `p1` and `p2` are only defined within the function. How would you tell, prove/test that the desired effect is achieved? – Yunnosch Feb 03 '22 at 21:26
  • You need to pass in pointers to pointers. That is `int **`. See the duplicate post for more details. – kaylum Feb 03 '22 at 21:26

1 Answers1

1

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;
}
Vlad from Moscow
  • 301,070
  • 26
  • 186
  • 335