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 following codes:
int n[5] = {3,6,9,12,15};
int *ptr = n;
ptr++;
printf("%d", *ptr); //Needless to say, the output will be 6
My assumption: The output above is 6 because ptr++
means ptr = ptr + 1
I am changing the value of ptr which is the address of n[0]
.
Now we take a look at the following scenario:
int n[5] = {3,6,9,12,15};
int *ptr = n;
*ptr++;
printf("%d", *ptr); //Why is the output still 6?
My question is: How do we interpret *ptr++
? Does it means:
- *ptr = *ptr + 1 or
- *ptr = ptr + 1 or
- ptr = ptr + 1 or what?
By the way, when I print out values of n
, it is still 3,6,9,12,15
.
Sorry for 2nd question:
How shall we interpret *++ptr
and ++*ptr
then?
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
http://www.difranco.net/compsci/C_Operator_Precedence_Table.htm
Expression
have value
before incrementing
ptr
and thenptr
is increment itself. There is no sense to writebecause the value of expression that is
*ptr
before incrementing ofptr
is not used. So in fact the result of these expressions (expression-statements)and
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.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.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*
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.