When functions are being called I often see the ampersand in front of the pointer in the function parameter.
E.g.
int *ptr;
randomFunction(&ptr);
I have done some research and found that this means that the function uses pointers to pointers. Is the &
sign in front of a pointer used just to indicate this or does it do something else?
An ampersand is a sign for the word and. It's written or typed as the symbol &. It's a modification of the term “and per se and,” which has Latin origins. The ampersand can indicate that the listed items are grouped together as part of a name.
An ampersand is a symbol (&) representing the word and. The ampersand was included in the Old English alphabet, and the term is an alteration of and per se and.
Noun. The symbol @; at sign.
The most common symbolism of an ampersand in interior home design is as a symbol of commitment: “You & Me.” You've probably seen ampersands in wedding decor as well. It shows that two people are joined — they are each others' “and,” meaning there is not one without the other.
&
is the reference operator, and can be read as address of
. In your example, it will get another pointer, that is the address of the pointer given as it's argument, i.e. a pointer to the pointer.
Look at the following example:
int **ipp;
int i = 5, j = 6, k = 7;
int *ip1 = &i, *ip2 = &j;
ipp = &ip1;
You will get:
In the above example, ipp
is a pointer to pointer. ipp
stores the address of ip1
and ip1
stores the address of i
.
You can check out Pointers to Pointers for more info.
Take a step back. The fundamental rules of pointer operators are:
*
operator turns a value of type pointer to T
into a variable of type T
.&
operator turns a variable of type T
into a value of type pointer to T
.So when you have
int *ptr;
ptr
is a variable of type pointer to int
. Therefore *ptr
is a variable of type int
-- the *
turns a 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
is a 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 is the same variable as ptr
. The *
is the inverse of the &
.
Make sense?
It helps to think of "&" this way. int function_name ( &( whatever ) ); You are passing the address of ( whatever ). Whatever can be a number of things: an elementary variable. a function. a structure. a union. an array. You should mentally translate "&" to "take the address of". So your example means : pass a COPY of the address of the address of the variable ptr of type int!
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