The asterisk is the dereference operator, that is, it takes the value that is in that address. It can only be used on pointers to give correct results.
*p
is to get the value of the address of p
, therefore in this case the p
is the address of i
which you already know, then it takes the value 5 and then sum 2 giving 7.
Then he does something unnecessary, I believe only to demonstrate the functioning. He’s picking up the address of p
(&p
), and with it is taking the value of this address through the *
(*&p
) returning to have the address contained in p
, so get your i
who was in p
, then he again takes the value of i
(**&p
). So there are 3 operators there: * * & p
or if you prefer (*(*(&p)))
.
The other read like this 3 * (*p)
. The beginning is simple is basic arithmetic that you already know, and what comes next you have already learned above. It is taking the value that is in the address of p
which 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 to better view:
#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
}
Behold working in the ideone. And in the Coding Ground. Also put on the Github for future reference.
And if you’re wondering if the *
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 way to access the value of a pointer when we are accessing a pointer. It’s confusing, it shouldn’t be like this, but that’s how language was conceived. The 3**p
demonstrates this well, the same symbol is doing two completely different operations.
It has explanation for all taste ;) So it is good at Sopt.
– Maniero
Yes, I thank each of the answers.
– Eduardo Cardoso