Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ function parameter takes an address of a pointer as an argument. How is this used? What is it for?

Imagine a function like this:

 function(Human *&human){
      // Implementation
 }

Can you explain what exactly a *& is? And what would it be used for? How is different than just passing a pointer or a reference? Can you give a small and explanatory sample?

Thank you.

like image 879
Koray Tugay Avatar asked Dec 20 '12 21:12

Koray Tugay


People also ask

How can a function pointer be an argument?

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. When you use pass-by-pointer, a copy of the pointer is passed to the function.

How are pointer arguments to functions passed in C?

Example: Passing Pointer to a Function in C ProgrammingWhen we pass a pointer as an argument instead of a variable then the address of the variable is passed instead of the value. So any change made by the function using the pointer is permanently made at the address of passed variable.

How can we pass a pointer as an argument to a function explain with example?

Example 2: Passing Pointers to Functions Here, the value stored at p , *p , is 10 initially. We then passed the pointer p to the addOne() function. The ptr pointer gets this address in the addOne() function. Inside the function, we increased the value stored at ptr by 1 using (*ptr)++; .

Why do we need to use a pointer to pointer as an argument of a function?

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

It is like a double pointer. You're passing the pointer by reference allowing the 'function' function to modify the value of the pointer.

For example 'human' could be pointing to Jeff and function could modify it to point to Ann.

Human ann("Ann");

void function(Human *& human)
{
    human = &ann;
}

int main()
{
    Human jeff("Jeff");
    Human* p = &jeff;
    function(p);  // p now points to ann
    return 0;
}
like image 86
Mustafa Ozturk Avatar answered Nov 15 '22 07:11

Mustafa Ozturk