Inference from pointers * ++ p and ++ * p

I don't understand why I am getting output 1, 2, 3 for the code below. I believe it should be 1, 2, 2. What is the reason for the first exit?

Also, let me point out that there are other questions pertaining to this kind of pointer arithmetic and dereferencing, but the answers to these questions suggest that the output should be 1, 2, 2.

int main()
{
    int p[3] = {1,2,3};
    int *q = p;
    printf("%d\n", *q);
    printf("%d\n", *++q);
    int x = ++*q;
    printf("%d\n", *q);
}

      

+3


source to share


3 answers


int p[3] = {1,2,3};
int *q = p;
printf("%d\n", *q);

      

q

indicates item 1.the above prints 1

printf("%d\n", *++q);

      

q

indicates item 2.The above prints are 2.



int x = ++*q;

      

Element 2. increases from 2 to 3.

printf("%d\n", *q);

      

q

indicates item 2.the above prints 3.

+5


source


*++q

parsed as *(++q)

; the result ++q

(which is q + 1

) is dereferenced, and as the side effect increases q

,

++*q

parsed as ++(*q)

; the result *q

(which is 2

) is the operand ++

that gives 3

. As a side effect, it increases *q

.

Remember that both postfix and prefix ++

have a result and a side effect ', and that a side effect should not be applied immediately after evaluating the expression. IOW,

a = b++ * ++c;

      



will be evaluated as

a = b * (c + 1);

      

but b

also c

does not need to update to the next point in the sequence.

+1


source


Hi,


         int p[3] = {1,2,3};
            int *q = p;
            printf("%d\n", *q); // The output for this line is 1
            printf("%d\n", *++q); // Pre Incrementing the 1 which becomes 2
            int x = ++*q;

     // Here we are making the x point to same location as q and then we are
    incrementing the location of the address q. Like q is pointing to the next location and so is the x.Hence the *q gives us 3 which is the value of the incremented location.



 printf("%d\n", *q);

Hope it is helpful

      

-1


source







All Articles