problem with pointers

#include<iostream>
using namespace std;

void update(int *p,int *q) {
*p=(*p)+(*q);
*q=(*p)-(*q);
}

int main() {
int a, b;
cin>>a;
cin>>b;
update(&a,&b);
cout<<a;
cout<<b;

return 0;
}


i am trying above code it uses concept of pointers but not getting the expected output what wrong here
input
9
5
expected output
14
4
getting output as 115
If you expect the output to be on different lines, you need to output line-endings, such as endl

I expect the output of your code to be 149, and that's what I see: http://ideone.com/oyaz8y

Note that in the function update, when you are assigning a new value to q, you are using the value of p that you already changed on the previous line. The calculation is not q=9-4 , but is q=15-4
Last edited on
how can i get the expected ans by
applying the pointers concept?
Since you want the value of p before you change it, you're going to have to use a temporary.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
#include<iostream>
using namespace std;

void update(int *p,int *q) 
{   int oldp = *p;
    *p = oldp + (*q);
    *q = oldp - (*q);
}

int main() 
{   int a, b;
    cin>>a;
    cin>>b;
    update(&a,&b);
    cout<<a << endl;
    cout<<b << endl;
    system ("pause");
    return 0;
}
9
5
14
4
Topic archived. No new replies allowed.