Saturday, August 6, 2016

Pointers - III - (Arithmetic Operations on Pointers)


Arithmetic operations on Pointers- Let us see how the pointers behave on performing arithmetic operations such as addition and subtraction on them.
We will take an example where we add 10 to a pointer, and then subtract 10 from the same.



Let us see the output.

 
As we can see , on adding 10 to ptr, ptr has gone 40 bytes away from its previous location.

Since ptr is a pointer to an int and int stores 4 Bytes, adding 10 adds to a total of 10*4= 40 Bytes. Same with subtraction.

For a pointer to a char, same rule holds good and adding/subtracting 10 will render to a total addition/subtraction of 10*1=10 Bytes to/from the address location.

What about an arithmetic operation on a void * pointer?
The behaviour is same as a pointer to a char. However, such an operation is not recommended as per the C standards. Explore it for more info.

++,-- operations on pointers- You must have been familiar with the usage of ++(increment) and –(decrement) operations by now in both pre- and post- form with normal variables.

Now let us perform these operations on pointers and see the outputs. Remember that the rules of operators' precedence will apply here.


Various such operations are possible :-
Consider 'ptr' as a pointer , following are some operations possible on ptr.
  • *ptr++
  • *(ptr++)
  • (*ptr)++
  • ++(*ptr)
  • ++*ptr
  • *++ptr
  • *(++ptr)

We will demonstrate this with the help of a simple and short program :

Let us see the output :


Keeping in place various rules of operators' precedence and post & pre increment, the above output seems quite logical.
*ptr++ and *(ptr++) are the same, because evaluation is simply done right-to-left in when no parenthesis is used. But , when a parenthesis is used as in (*ptr)++,and ++(*ptr), the parenthesis is evaluated first, which is again as per the operators' precedence rule.
++*ptr , *++ptr and *(++ptr) show output as expected. Last two expressions are the same.

Please note in the above snapshot that after the expression, *++ptr, z becomes 10. This is not because of linear increment of z from the value of 5 onwards. This 10 is the value stored in y, whose address is now being pointed to by ptr as a result of total increment by 4 Bytes so far.

This is all from the section of Arithmetic Operations on Pointers. Publish comments and let me know if you have any doubt or need any clarification on any of the topics on this Blog.


No comments:

Post a Comment