C - pointer behavior with pre and post increment

前端 未结 6 1321
日久生厌
日久生厌 2021-01-22 08:50

In am doing some experiment in C pointers and trying to understand its behaviour. The following are my assumptions for the below codes. Correct me if I am wrong. I have the foll

相关标签:
6条回答
  • 2021-01-22 09:03

    The order of precedence is also compiler dependent. It may change depending upon compilers. Better use a parenthesis to be sure of output

    0 讨论(0)
  • 2021-01-22 09:06

    Because of the operator precedence *pt++; is the same as *(ptr++); so it increments the pointer, then dereference the pointer and does nothing.

    0 讨论(0)
  • 2021-01-22 09:12

    Expression

    *ptr++;
    

    have value

    *ptr
    

    before incrementing ptr and then ptr is increment itself. There is no sense to write

    *ptr++;
    

    because the value of expression that is *ptr before incrementing of ptr is not used. So in fact the result of these expressions (expression-statements)

    ptr++;
    

    and

    *ptr++;
    

    is the same.

    As for expressions *++ptr and ++*ptr then in this expression *++ptr at first ptr is incremented ( that is it will point to the second element of the array) and then dereferenced and its value is the value of the second element. In this expression ++*ptr at first the value of the first element of the array is returned (that is 3) and then this value is incremented and you will get 4.

    0 讨论(0)
  • 2021-01-22 09:19

    Both ptr++ and *ptr++ increment the pointer after they have returned, in the first case, the previous address to which ptr was pointing, and in the second case, the value from this address. You do not do anything with the results, so you do not see the difference.

    *++ptr will first increment ptr, then returns the value to which it now points.

    ++*ptr will get the value to which ptr points, increment it, and then return.

    0 讨论(0)
  • 2021-01-22 09:23

    Please check the link below: Difference between ++*argv, *argv++, *(argv++) and *(++argv)

    You need to know about operator precedence in-order to understand what is going on here.

    ++ operator has higher precedence over *

    0 讨论(0)
  • 2021-01-22 09:24

    It is due to operator precedence in C. The below link may help you

    Increment or decrement operator has higher precedence that dereference operator.So your

    *ptr++; is similar to *(ptr++)
    

    http://www.difranco.net/compsci/C_Operator_Precedence_Table.htm

    0 讨论(0)
提交回复
热议问题