-2
void update(int *a,int *b) {
    *a=*a+*b;
    *b=*a-*b;  
}

int main() {
    int a, b;
    int *pa = &a, *pb = &b;

    scanf("%d %d", &a, &b);
    update(pa, pb);
    printf("%d\n%d", a, b);

    return 0;
} 

i wanted to store the sum of a & b in a and diff. of a & b in b using pointers pointing towards a & b,so i tried it in the way given,the addition part is working fine bt i don't know why subtraction is not working??

user438383
  • 5,716
  • 8
  • 28
  • 43
  • 4
    The pointers are not relevant to the problem. The problem is that you are calculating `a - b` *after* modifying `a` to hold the sum. – Raymond Chen Mar 22 '23 at 21:47
  • How do you know it is not working? – user253751 Mar 22 '23 at 22:01
  • This code is word-for-word identical to [how to get sum and absolute difference in the same function?](https://stackoverflow.com/questions/75207177/how-to-get-sum-and-absolute-difference-in-the-same-function). The only difference is that this one omits the `#include ` – Raymond Chen Mar 22 '23 at 23:22

3 Answers3

4

After you've done *a=*a+*b; the value of *a is changed, so *b=*a-*b; will use that new value.

You can solve it by saving the result from the first calculation and assigning it to *a later ...

void update(int *a,int *b) {
    int tmp = *a + *b;       // save for later
    *b = *a - *b;
    *a = tmp;                // use here
}

... or by negating the effect of + *b in the first calculation when doing the second calculaton:

void update(int *a, int *b) {
    *a = *a + *b;
    *b = *a - *b - *b;
}
Ted Lyngmo
  • 93,841
  • 5
  • 60
  • 108
2

*a=*a+*b; updates the object thst a points to. Then *b=*a-*b; uses the updated value, not the original value.

To use the original value, you must create another variable and use it to hold either the new or the old value of *a temporarily.

Eric Postpischil
  • 195,579
  • 13
  • 168
  • 312
2

When you pass by a pointer, assigning to the dereferenced pointer changes the original object. You need to store the result in the intermediate variables.

void update(int *a,int *b) 
{
    int sum = *a+*b;
    int diff = *a-*b;
    *a = sum;
    *b = diff;  
}

int main() {
    int a, b;

    scanf("%d %d", &a, &b);
    update(&a, &b);
    printf("%d\n%d", a, b);

    return 0;
} 

https://godbolt.org/z/Yfr6P6q5r

0___________
  • 60,014
  • 4
  • 34
  • 74