What does the ampersand "&" do before pointers?

When functions are called, I often see an ampersand before the pointer in the function parameter.

eg.

int *ptr; randomFunction(&ptr); 

I did some research and found that this means that the function uses pointers for pointers. Is the & before the pointer used only to indicate this, or does something else?

+6
source share
4 answers

This is a pointer to a pointer.

& is a reference operator and can be read as address of . In your example, it will receive another pointer, that is, the address of the pointer specified as its argument, that is, a pointer to a pointer.

Take a look at the following example:

 int **ipp; int i = 5, j = 6, k = 7; int *ip1 = &i, *ip2 = &j; ipp = &ip1; 

You'll get:

enter image description here

In the above example, ipp is a pointer to a pointer. ipp stores the address ip1 and ip1 stores the address i .

You can check Pointers to pointers for more information.

+20
source

Take a step back. The basic rules for pointer operators are:

  • The * operator turns a value of type pointer to T into a variable of type T
  • The & operator turns a variable of type T into a value of type pointer to T

So when you

 int *ptr; 

ptr is a variable of type pointer to int . Therefore *ptr is a variable of type int - * turns the pointer into a variable. You can say *ptr = 123; .

Since ptr is a variable of type pointer to int , &ptr is a value - not a variable - of type pointer to pointer to int :

 int **pp = &ptr; 

&ptr - value of type pointer to pointer to int . pp is a variable of type pointer to pointer to int . *pp is a variable of type pointer to int , and in fact it is the same variable as ptr . * is the inverse of & .

Make sense?

+3
source

It helps to think about the & here. int function_name (& (whatever)); You pass the address (whatever). Whatever it is: an elementary variable. function. structure. union. an array. You must mentally translate & to take an address. So your example means: pass a COPY of the address of the address of the variable ptr of type int!

+1
source
 Int *ptr; 

& ptr returns the address of the ptr pointer variable. In short, a double pointer or int ** contains the address ptr with & ptr.

0
source

All Articles