Reputation: 12890
I am confused between these two functions:
void Swap_byPointer1(int *x, int *y){
int *temp=new int;
temp=x;
x=y;
y=temp;
}
void Swap_byPointer2(int *x, int *y){
int *temp=new int;
*temp=*x;
*x=*y;
*y=*temp;
}
Why Swap_byPointer2
succeeds to swap between x and y, and Swap_byPointer1
does not?
Upvotes: 13
Views: 422
Reputation: 12092
Initial setup of the functions, (common for both) (mock values)
(Assumption : The values written outside the boxes are address.)
Function swap_byPointer1,
Function swapby_Pointer2,
Hope this helped to get a picture of whats happening, Cheers!
Upvotes: 7
Reputation: 63200
In your first function you're swapping the pointers themselves, and in the second you're swapping the values of what the pointers point to, ie pointers dereferenced.
If you want to change what a pointer points to, you should pass a pointer to a pointer (ie int**x
) and change the second pointer.
Like so
void Swap_byPointer1(int **x, int **y){
int *temp;
temp=*x;
*x=*y;
*y=*temp;
}
Upvotes: 7
Reputation: 41331
The first snippet swaps the memory addresses which are the values of the pointers. Since the pointers are local copies, this has no effect for the caller.
Rewritten without a memory leak:
void Swap_byPointer1(int *x, int *y){
//e.g x = 0xDEADBEEF and y = 0xCAFEBABE;
int *temp=x;
x=y;
y=temp;
//now x = 0xCAFEBABE and y = 0xDEADBEEF
}
The second swaps the pointees (objects that the pointers point to).
Rewritten without a memory leak:
void Swap_byPointer2(int *x, int *y){
//e.g *x = 100 and *y = 200
int temp =*x;
*x=*y;
*y=temp;
//now *x = 200 and *y = 100
//there are now different values at the original memory locations
}
(Pointers can point to dynamically allocated objects, but don't have to. Using a pointer does not mean there has to be a new-allocation. Pointers can point to objects with automatic lifetime as well.)
Upvotes: 5
Reputation: 612964
Because the parameters are passed by value. In the first code sample all you do is swap local copies of the pointers. The second example actually writes to the pointees.
Better still would be to use pass by reference and avoid heap allocation by using a stack allocated temp int.
void SwapByRef(int &x, int &y)
{
int temp=x;
x=y;
y=temp;
}
....
int x=1;
int y=2;
SwapByRef(x, y);
As others have pointed out, both of your code samples leak memory because temp is never deleted. For a simple int like this, just use a stack allocated local int variable for your temp.
Upvotes: 6
Reputation: 11896
The first function is just reassigning the local copy of pointers, not modifying the underlying values. When it returns, it will have had no effect (other than allocating a new int)
Upvotes: 4