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?
Pass-by-pointer means to pass a pointer argument in the calling function to the corresponding formal parameter of the called function. The called function can modify the value of the variable to which the pointer argument points.
The difference between pass-by-reference and pass-by-pointer is that pointers can be NULL or reassigned whereas references cannot. Use pass-by-pointer if NULL is a valid parameter value or if you want to reassign the pointer. Otherwise, use constant or non-constant references to pass arguments.
References are usually preferred over pointers whenever we don't need “reseating”. Overall, Use references when you can, and pointers when you have to. But if we want to write C code that compiles with both C and a C++ compiler, you'll have to restrict yourself to using pointers.
You pass a pointer to pointer as argument when you want the function to set the value of the pointer. You typically do this when the function wants to allocate memory (via malloc or new) and set that value in the argument--then it will be the responsibility of the caller to free it.
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;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With