Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Passing by pointer

Tags:

c++

pointers

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?

like image 689
Aan Avatar asked Nov 22 '11 16:11

Aan


People also ask

What is passing by pointer?

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.

Is Passing By pointer vs reference?

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.

Is better to pass by reference or pointer C++?

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.

When should you pass a pointer?

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.


1 Answers

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;
}
like image 192
Tony The Lion Avatar answered Oct 07 '22 00:10

Tony The Lion