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
The order of precedence is also compiler dependent. It may change depending upon compilers. Better use a parenthesis to be sure of output
Because of the operator precedence *pt++;
is the same as *(ptr++);
so it increments the pointer, then dereference the pointer and does nothing.
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.
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.
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 *
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