0
Explain the difference between *ptr++ and ++*ptr same?

Open 1 Answers 270 Views Technology
Explain the difference between  *ptr++ and ++*ptr same?

1 Answer

0
Both expressions are different. Let’s see a sample code to understand the difference between both expressions.

#include <stdio.h>
int main(void)
{
    int aiData[5] = {100,200,30,40,50};
    
    int *ptr = aiData;
    
    *ptr++;
    
    printf("aiData[0] = %d, aiData[1] = %d, *piData = %d", aiData[0], aiData[1], *ptr);
    
    return 0;
}
Output: 100, 200, 200

Explanation:
In the above example, two operators are involved and both have different precedence. The precedence of post ++ is higher than the *, so first post ++ will be executed and above expression, *p++ will be equivalent to *(p++). In another word you can say that it is post-increment of address and output is 100, 200, 200.

#include <stdio.h>
int main(void)
{
    int aiData[5] = {100,200,300,400,500};
    int *ptr = aiData;
    ++*ptr;
    printf("aiData[0] = %d, aiData[1] = %d, *ptr = %d", aiData[0], aiData[1], *ptr);
    return 0;
}
Output: 101 , 200 , 101

Explanation:
In the above example, two operators are involved and both have the same precedence with a right to left associativity. So the above expression ++*p is equivalent to ++ (*p). In another word, we can say it is pre-increment of value and output is 101, 200, 101.
by (279k points)
...