Pointer Question

I'm working on a pointer question on HackerRank.The objective is to add and subtract two pointers. I am a little confused on why my *tempA is storing my sum.


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
#include <iostream>
#include <stdio.h>
using namespace std;
/*
Q) What is a pointer?
A) A pointer is a data type that points to another value stored in mem
A) A pointer is a variable that holds a memorey address
-------------------------------------------------------------------------
-------------------------------------------------------------------------
-------------------------------------------------------------------------
& - address of operator
* - contents of operator

using the * operator
The contents of the derefernce operator allows us to get the value stored
at the address held by the pointer

*/
void update(int *a,int *b) {
    // Complete this function    
    int addition;//for the a+b
    int subtraction;//for a-b
    int absoulte;//for abs()
    int *tempA=a;//to temp hold a
    int *tempB=b;//to temp hold b
    
    cout<<"the contents of tempA is "<<*tempA<<endl;
    cout<<"the contetnts of tempB is "<<*tempB<<endl;
    addition=*tempA+*tempB;
    *a=addition;
    cout<<"The result of the sum is "<<*a<<endl;

   cout<<"the contents of tempA is "<<*tempA<<endl;//tmpa is equal to the addition
   cout<<"the contents of tempB is "<<*tempB<<endl;
    subtraction=(*tempA-*tempB);//subt5raction is equaling *a
    cout<<"the sub is "<<subtraction<<endl;
    absoulte=abs(subtraction);
    *b=absoulte;

}

int main() {
    int a, b;
    int *pa = &a, *pb = &b;//pointer pa points to the address of a
                           //pointer pb points to the address of b
    
    scanf("%d %d", &a, &b);//same this as cin>>
                           //takes in the user input for a and b
                          //i guess scanf stores the two ints into the address of a and b
                          
    update(pa, pb);
    printf("%d\n%d", a, b);

    return 0;
}


It looks like the addition is working, but not the subtraction.
It's working properly. Line 30 stores addition to *a. Since tempA and a point to the same int, that means *tempA will show addition too. Does that help?
Thank you for your reply. I think I understand what you're saying. That means I won't be able to make 2 new temp variables for the subtraction part. for example
1
2
3
4
 int *subA=a;
 int *subB=b;
 subtraction=(*subA-*subB);   

because, as you said, it's still pointing to the same int
Could you give me a hint in the right direction?
You need to process the subtraction before you change one of the pointer variables. I.e. before line 30.
Topic archived. No new replies allowed.