I'm newbie on C. I need to understand what each of the values printed on the screen means by the following code:
#include<stdio.h>
int main()
{
int x = 10;
int *ptr = &x;
printf("%d %d %d\n", *ptr,**&ptr, 2**ptr);
return 0;
}
Output(GCC):
10 10 20
Here, I have declared variable x and ptr point to x variable. So, *ptr printed value of x. But I could not understand the values of **&ptr and 2**ptr.
Thanks in advance.
Here, * and & operators cancel effect of each other when used one after another.
**&ptr is the same as *ptr and here, ptr hold the address of x variable. So, print the value of x here.
2**ptr is interpreted as 2 * (*ptr). So, 2 * (10) is equal to 20.
**&ptr
& and * are unary operators which have an opposite meaning 1 from the other.
&(lvalue) means to return the address of the corresponding lvalue while *(lvalue) means to return the value from the address pointed by lvalue, considering the type of lvalue, in order to know how to dereference it.
Visually the meaning of these operators looks like this (my talent in artist-mode of emacs is not too big):
+----------------+
| ptr = *&ptr |
+--------------+-+
/ \
/ \
&ptr \
+----------------+
| *ptr |
+----------------+
/
/
ptr
Note that I marked inside the box the right value, while outside the box the addresses of memory of the left values of the corresponding memory locations.
Now when you write *&(lvalue), it means to get the value from the address of lvalue, which is written shortly lvalue.
So **&ptr means *ptr -- namely the value from the adress pointer by ptr, dereferenced as integer, in your case 10.
2**ptr
The lexer will split the code in tokens and the parser will build a tree like that:
(2) * (*ptr)
In this case the result will be 2 times the value from the adress of ptr, in your case 20.
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