The asterisk is the dereference operator , that is, it takes the value that is in that address. It can only be used in pointers to give correct results.
*p
is to get the value of the address of p
, in this case the p
is the address of i
you already know, then it takes the value 5 and then adds 2 giving 7 .
Next he does something unnecessary, I believe only to demonstrate the operation. It is getting the address of p
( &p
), and with it it is getting the value of this address through *
( *&p
) returning having the address contained in p
, so it returns the address of i
that was in p
, then it again takes the value of i
( **&p
). Then there are 3 operators there: * * & p
or if you prefer (*(*(&p)))
.
The other read 3 * (*p)
. The beginning is simple is basic arithmetic you already know, and what comes next has already learned above. It is getting the value that is at the address of p
that we know is worth 5 (the value of i
) and multiplies by 3.
The latter is a mixture of the second and third.
Separating operations for better viewing:
#include <stdio.h>
int main() {
int i = 5;
int *p = &i;
printf("%u\n", p); //é o endereço de i
printf("%d\n", *p); //é o valor de i obtido pelo endereço que está em p
printf("%d\n", (*p) + 2); //pega o valor de i e soma 2
printf("%d\n", (&p)); //pega o endereço de p
printf("%d\n", (*(&p))); //com o endereço de p pega o valor dele, que é o endereço de i
printf("%d\n", *(*(&p))); //então pega o valor de i, isto é o mesmo que *p
printf("%d\n", 3 * (*p)); //multiplica 3 pelo valor de i, é o mesmo que 3 * i
printf("%d\n", *(*(&p)) + 4); //soma 4 em i através de uma fórmula desnecessária
}
See running on ideone . And no Coding Ground . Also I placed GitHub for future reference .
And if you're wondering if *
has different meaning depending on the context, yes, it has, it can be used as a multiplier when we are talking about normal values or it can have the form of accessing the value of a pointer when we are accessing a pointer. It is confusing, it should not be so, but that is how language was conceived. 3**p
shows this well, the same symbol is doing two completely different operations.