Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the meaning of "**&ptr" and "2**ptr" of C pointer?

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.

like image 311
skc Avatar asked Oct 28 '17 08:10

skc


Video Answer


2 Answers

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.

like image 161
msc Avatar answered Sep 23 '22 14:09

msc


**&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.

like image 33
alinsoar Avatar answered Sep 20 '22 14:09

alinsoar