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.
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.
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.
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)++; .
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.
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;
}
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