How to perform arithmetic operations on C++ pointers?

- March 18, 2018
We can perform addition and subtraction (two arithmetic) operations on pointers. A pointer can be incremented or decremented, It's mean that we can add or subtract integer value to and from the pointer. Similarly, a pointer can be subtracted or added to and from another.
The arithmetic (addition and subtraction) operations are different than that of ordinary arithmetic operations. The following piece of code describes the pointer arithmetic:
      int *p;
      int x;
      p = &x;
Suppose, the memory address allocated to variable 'x' is 100 which is assigned to 'p'. Both variables (p and x) are of 'int' type. The size of 'int' type is two bytes. When the statement "p++;" is executed, the contents of 'p' will be 102 (instead of 101). When an integer is added or subtracted from a pointer, the pointer is not incremented or decremented by that integer but it's incremented or decremented by integer times the size of the object to which the pointer refers. The size of the object depends upon the its data type (int, float etc.). So, the statement "p++;" is executed as shown in the following pictorial form:
arithmetic operations on pointer

The pointer points to the memory location of the next element of its base type, each time a pointer is increment by 1. In the same way, when a pointer decrement by 1, it points to the location of the previous element. The increment and decrement operations are performed as normal in the case of pointers to characters.
All the pointer variables are incremented or decremented according to the size of data type they point to. For example, if pointer variable 'pp' that points to 'float' data type, holds the memory address 4000 and value 2 is added to it as:
pp = pp +2;
The value 4008 (4000 + 2 * 4 = 4008) will be assigned to pointer variable 'pp', after the execution of above statement:
execution of pointer variable