You are here:

C++/complicated syntax

Advertisement


Question

hello
i was working with linked lists and dynamic memory
when i add a new node to the list
i have the following function prototype

void addnode(structtype*& head)
{
//code goes here
}

what does the *& mean?

thanks

Answer
*& is a pointer variable containing the reference of the
address. so any modification to this will modify the variable
accordingly
An example would make it clear:

   void allocate(int *x)
{
x  = new int;
}
main()
{
int *p;
allocate(p);
*p = 6;
}

The above code snippet results in an access violation error stating
"data space never allocated" . This is because the address to the new
int is never passed back to main. so the main will have no clue of
where p is.

consider the below snippet:

void allocate(int *&x)
{
x = new int;
}
main()
{
int *p;
allocate(p);
*p = 1;
}

Here the pointer contains the reference of the address of the variable
x.so when the address is captured in p and memory is alloacted at a
particular location the main is aware of all this becuase it has
called the allocate function using a reference. (which contains a
reference parameter or an alias of the variable being passed from
main). So the address is returned back to main.


Does this clarify your doubt?

C++

All Answers


Answers by Expert:


Ask Experts

Volunteer


Saikrishna

Expertise

I can answer questions in C (Basic and a little of advanced). I can't answer questions related to multi threading

Experience

2.6 years

Education/Credentials
I am a B-tech graduate majored in computer science.

©2016 About.com. All rights reserved.