0
swap variable values with pointer
so i have 2 variables x,y; pointer p1 stores x address and using p1 we make x value 99 then using p1 we point to y and make its value -300 then we create int temp and pointer p2 THIS IS THE PROBLEM: i need to swap values of variables x, y while using only existing pointers and int temp ( after swapping it should be x=-300; y=99) this is what i have so far: https://code.sololearn.com/cs6l8leG224j/#cpp
5 Respuestas
0
thing is, at this point (before swapping) p1 holds y's address/value, somehow i need to access x's address/value without using x variable
0
it says in the original post that p2 is not assigned to any variable
0
you can do it using a single pointer and a temp variable or just using two pointers.
0
using one pointer and a temp variable:-
int main(){
int x, y, temp, *p1;
p1 = &x;
*p1 = 99;
p1 = &y;
*p1 = -300;
cout <<"Before swap " << x << " " << y << endl ;
temp = *p1;
*p1 = x;
x = temp;
y = *p1;
cout << "After swap " << x << " " << y;
return 0;
}
0
using pointers only:-
int main() {
int x,y;
int *p1=&x;
*p1 = 99;
int *p2 =&y;
*p2 = -300;
cout << "Before swap" << x << " " << y << endl;
*p1 = *p1 + *p2 ;
*p2 = *p1 - *p2;
*p1 = *p1 - *p2;
cout << "After swap" << x << " " << y;
}