C meaning of (*++ptr) pointer

Meaning of (*++ptr) :


Consider the Following Example :

int n = 20 , *ptr ;
ptr = &n;
printf("%d",*++ptr);

Explanation :

  1. ‘++’ and ‘*’ both have Equal Precedence
  2. Associativity is from Right to Left ( Expression evaluated from R->L)
  3. Both are Unary (Operates on single operand )
  4. So ‘ ++ ‘ is Performed First then ‘ * ‘


Calculation of Answer :

* ++ptr   =  *(++ptr )
          =  *( 3060 )
          =  Value Stored at Location 3060

Live Program :

#include<stdio.h>
int main()
{
int n = 20 , *ptr ;
ptr = &n;
printf("%d",*++ptr);
return(0);
}

Output :

Garbage Value gets printed

Note :

  1. This operation should not be used in normal operation.
  2. Perform this operation if we have consecutive memory i.e Array.
  3. If we perform this operation in above example then we will get garbage value as we dont know the value stored at 3060.
  4. Consider following example to get idea , how *++ptr is used in Array -

How to use *++ptr in Array Program ?

#include<stdio.h>
int main()
{
int arr[5] = {10,20,30,40,50};
int *ptr ;
ptr = &arr;
printf("%d",*++ptr);
return(0);
}

Output :

20