Reputation: 39
In one of my lectures we had this function that adds elements to a non stl binary three. What does the *& do exactly? I know that & gets the address of a variable and that * allows us to access the value at a particular address. Do they have a different meaning when together? Also if I was to call this function in main, what do I do with the t
pointer?
void add(int n, elem *&t)
{
if (t==NULL) //ако е достигнат празен указател или дървото е празно
{
t=new elem;
t->key=n;
t->left=t->right=NULL; //left и right са NULL, тъй като новият елемент няма наследници
} else //ако достигнатото място е заето от друг елемент
{
if (t->key<n) //ако новодобавения елемент е по-голям от текущия, то указателя се измества надясно,извиква се рекурсивно add с указателя вдясно
add(n,t->right);
else
{
if (t->key>n) //с цел да се елиминират повтарящи се елементи се прави втората проверка
add(n,t->left); // извиква се рекурсивно add с указателя вляво
}
}
}
Here is the structure as well:
struct elem
{
char key;
elem *left; //lqv naslednik
elem *right; // desen naslednik
}*root=NULL; // v sluchai che nqma koren
Upvotes: 0
Views: 874
Reputation: 15511
In your case, it is a part of the elem*&
function parameter reference type. Used to pass an object of type elem*
by reference. Pointers are just like any other variables/objects. Passing them by reference allows us to change the pointer value in a function.
The elem* &t
in your void add(int n, elem *&t)
signature does not "get the address of a variable". It means the type of the function parameter is a reference type. It just so happens it is a pointer reference type in your case.
Do not confuse the address-of operator, which is &
with a reference type signature of T& param_name
. In your case, the T
is elem*
.
It could also mean: dereference the address of an object if used in the following context:
#include <iostream>
int main()
{
int x = 123;
std::cout << *&x;
}
Upvotes: 4