Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

c++ * and & at the same time

In my Data Structures in C++ class we're working on binary trees. Some of the code contains places where & and * are used at the same time (right next to each other) and it's very confusing.

void balance( AvlNode * & t )

is one example of a function definition in which this is used. What happens here with the * and &?

Edit: The answers to this have told me that I really know nothing about pointers and references, but the sources all say different things, like here for example calls * the dereference operator. Where can I find all of this information in one place? (not on stackoverflow preferably)

like image 561
Mitchell Carroll Avatar asked Sep 03 '25 01:09

Mitchell Carroll


2 Answers

Read from right to left1, reading & as a "reference to [a|an]" and * as a "pointer to [a|an]", so you get: "t is a reference to a pointer to an AvlNode".


1. For more complex cases, it's not always entirely right to left--it's from the name being declared outward to the type of the declaration. If you have multiple nested parentheses, you proceed right from name to a closing parenthesis, then left to the matching open parenthesis, then right from the place you last left off to the next closing parenthesis, and so on until you reach the outer-most level.

like image 92
Jerry Coffin Avatar answered Sep 05 '25 18:09

Jerry Coffin


The '&' character has a special meaning in C++ when it's used inside of a function declaration or definition. It means "pass the value by reference". When you "pass by reference" C++ will automatically create a reference of your variable when you pass it to the function, and then it will automatically dereference it inside the function.

So this function passes one variable t of type AvlNode * by reference. Hence, you have AvlNode * & t

So for example:

void balance( AvlNode * & t )
{...}

main()
{
   AvlNode * a = new AvlNode();
   balance(a);
}

is the same as:

void balance( AvlNode ** t_ptr )
{
   AvlNode * t = *t_ptr;
   ...
}

main()
{
   AvlNode * a = new AvlNode();
   balance(&a);
}
like image 32
Gillespie Avatar answered Sep 05 '25 16:09

Gillespie