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.
#include <iostream>
#include <stdio.h>
usingnamespace 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?