Increment and Decrement Operations on Pointer

We will see how it will work using one example:

main()
{
   int i = 258;
   int *ip;         //integer pointer
   char *cp;        //character pointer
   
   ip = cp = &i;
   printf("%d \n",*cp);
   cp = cp + 1;
   printf("%d \n",*cp);

   printf("ip = %u  ip+1 = %u \n",ip,ip+1);
   printf("cp = %u  cp+1 = %u \n",cp,cp+1);

}

Answer :

2
1
ip = 1000   ip+1 = 1016      //interger is 4byte in size
cp = 1000   cp+1 = 1004      //character is 1byte in size

 

Now we will see some cases in different conditions:

1. *p++

  • = *p p++
  • Here, it is the case of post increment. So, first *p will come to picture, that means firstly it will assign the value and then it will show increment in the p.

Example :

main()
{
   int i = 10, j , *p;
   p = &i;
 
   printf("p = %u \n",p);
   j = *p++;
   printf("i = %u j = %u  p = %u \n",i,j,p);
}

Answer :

p = 1004    //assume that starting address is 1004
i = 10 j = 10 p = 1008

2. ++*p

  • Here, value is increment that indicates not *p – value but i’s value.

Example :

main()
{
    int i = 10, j , *p;
    p = &i;
 
    printf("p = %u \n",p);
    j = ++*p;
    printf("i = %u j = %u p = %u \n",i,j,p);
}

Answer :

i = 11 j =11 p = 1004

3. *++p

  • Here address is incrementing because of it is pre – increment. If j = *++p ,j contains *++p ‘s address.

4. (*p)++

  • Here (*p) is incrementing, means value of i increment (i++).

5. ++(*p)

  • i is incrementing not *p.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

w

Connecting to %s

Powered by WordPress.com.

Up ↑

%d bloggers like this: