Shouldn't ptrj value be 4 after the execution of *ptrj++?
int j=3,*ptrj = NULL;
ptrj = &j;
*ptrj++;
printf("%i",*ptrj);
Shouldn't ptrj value be 4 after the execution of *ptrj++?
int j=3,*ptrj = NULL;
ptrj = &j;
*ptrj++;
printf("%i",*ptrj);
*ptrj++
is the same as *(ptrj++)
. What you expect is instead (*ptrj)++
. You should look up operator precedence to learn more about which operators that acts before others. To understand what ptrj++
does, you should read about pointer arithmetic. But here is a quick explanation:
*(ptrj++)
returns the value that ptrj
points to (3), and THEN increments ptrj
to point to the next value.
(*ptrj)++
returns the value that ptrj
points to (3), and THEN increments the value that ptrj
points at from 3 to 4.
This means that what you're printing is the value at address &j + 1
, which is the value that lies right after the variable j
in memory. and this is undefined behavior. As Sourav pointed out, you would get a warning that points you to this if you enable compiler warnings.
The only difference between *ptrj++
and ptrj++
is what it is returning. And since you don't use the return value, your code is equivalent to:
int j=3,*ptrj = NULL;
ptrj = &j;
ptrj++;
printf("%i",*ptrj);
If you compile the program with warnings enabled, you'll see
source_file.c:9:5: warning: value computed is not used [-Wunused-value]
*ptrj++;
^
That means, the value computation is useless.
In other words, according to the operator precedence *ptrj++;
is same as *(ptrj++);
, and as per the post-increment operator property, the value of the operation is the value of the operand, and the value is increased as the side-effect.
Quoting C11
, chapter
The result of the postfix
++
operator is the value of the operand. As a side effect, the value of the operand object is incremented (that is, the value 1 of the appropriate type is added to it). [....]
So, this is same as
*ptr;
ptr++;
If you want to increment that value at the address, you need to enforce the operator precedence by using explicit parenthesis, like
(*ptrj)++; // first get the value, then update the value.
*ptrj++
is equivalent to *(ptrj++).
desired output can be achieved using (*ptrj)++.
Please refer https://www.geeksforgeeks.org/c-operator-precedence-associativity/ to get how operator works.
Precedence of postfix ++ is higher than *. The expression *ptrj++ is treated as *(ptrj++) as the precedence of postfix ++ is higher than *.If you want to print 4 ( ie ptrj+1 ),You should use the following code:-
int j=3,*ptrj = NULL;
ptrj = &j;
(*ptrj)++;
printf("%i",*ptrj);
return 0;
To know more about operator precedence, refer follow link: https://en.cppreference.com/w/c/language/operator_precedence