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_byPointer1does not?
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:
The second swaps the pointees (objects that the pointers point to).
Rewritten without a memory leak:
(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.)