Pointer and References in C ++ as Arguments

What does it do?

void insertar (struct pila *&p);

      

Advantages of using it *&

compared to the fact that the method was declared like this:

void insertar (struct pila *p);

      

or like this:

void insertar (struct pila &p);

      

I know what *

is a pointer and &

is an address, but what about the method signature?

What is the advantage?

And what are they used for?

What is he doing?

+3


source to share


3 answers


You are mixing two meanings &

. This is the "address" operator used in the expression. That is, if you have int x;

, and you do &x

, you get an address x

. However, in type &

means that it is a reference type. These are two completely different concepts.

The following takes pila

by copying it into a function. The modification p

will only affect the copy inside the function:

void insertar(pila p);

      

The following is taken pila

by reference, so the object inside the function is the same as the outside one. Changing p

here will change the object that was passed in:

void insertar(pila& p);

      



The following outputs a pointer to pila

by copying the pointer into a function. Changing the pointer will have an effect inside the function. The object it points to is the same as outside:

void insertar(pila* p);

      

The following outputs a pointer to pila

by reference, so the pointer inside the function is the same as the outside one. If you change the pointer, you also change the pointer outside:

void insertar(pila*& p);

      

+5


source


Here &

is a link. A *&

is pretty much like **

. This will allow you to change the pointer.



int u = 3;

void change( int *& p ) {
    p = &u;
}

void main() {
    int *p;
    change( p );
    // p == &u
}

      

+1


source


*&

is a reference to a pointer in your example. In short, you can change the data indicated by the pointer and the pointer itself. Example:

int global1 = 0, global2 = 1;
void func(int*& p)
{
    *p = 42;
    p = &global1;
}

int main()
{
    int* p = &global2;
    func(p); // Now global2 == 42 and p points to global1 (p == &global1).
}

      

0


source







All Articles