Search code examples
cpointerssubtraction

How To Find Difference Of Two Pointer Values


I am learning C programming and currently on Pointers.

#include <stdio.h>

void update(int *a,int *b) {
        *a = *a + *b;
        //*b = *a - *b;
        printf("%d", *a - *b);

}

int main() {
    int a = 4, b = 5;
    int *pa = &a, *pb = &b;
    
    scanf("%d %d", &a, &b);
    update(pa, pb);
 
    return 0;
}

I have no idea why it prints 4 instead of -1. I want to assign their difference in pointer *b. Any tip is appreciated.


Solution

  • In your case,

        *a = *a + *b;
        cout << *a - *b;
    

    adds the value of *b to *a, and then subtract *b, so it's essentially the same as

        cout << *a + *b -*b;    
    

    or

        cout << *a;
    

    which is 4 (assuming you entered the same value with which you initialized the variables in the code).