Which operations are permitted on pointers?

Following are the operations that can be performed on pointers:

  • Incrementing or decrementing a pointer: Incrementing a pointer means that we can increment the pointer by the size of a data type to which it points.

There are two types of increment pointers:

1. Pre-increment pointer: The pre-increment operator increments the operand by 1, and the value of the expression becomes the resulting value of the incremented. Suppose ptr is a pointer then pre-increment pointer is represented as ++ptr.

Let’s understand this through an example:

  1. #include <iostream>  
  2. using namespace std;  
  3. int main()  
  4. {  
  5. int a[5]={1,2,3,4,5};  
  6. int *ptr;  
  7. ptr=&a[0];  
  8. cout<<“Value of *ptr is : “<<*ptr<<“\n”;  
  9. cout<<“Value of *++ptr : “<<*++ptr;  
  10. return 0;  
  11. }  

Output:

Value of *ptr is : 1
Value of *++ptr : 2

2. Post-increment pointer: The post-increment operator increments the operand by 1, but the value of the expression will be the value of the operand prior to the incremented value of the operand. Suppose ptr is a pointer then post-increment pointer is represented as ptr++.

Let’s understand this through an example:

  1. #include <iostream>  
  2. using namespace std;  
  3. int main()  
  4. {  
  5. int a[5]={1,2,3,4,5};  
  6. int *ptr;  
  7. ptr=&a[0];  
  8. cout<<“Value of *ptr is : “<<*ptr<<“\n”;  
  9. cout<<“Value of *ptr++ : “<<*ptr++;  
  10. return 0;  
  11. }  

Output:

Value of *ptr is : 1
Value of *ptr++ : 1
  • Subtracting a pointer from another pointer: When two pointers pointing to the members of an array are subtracted, then the number of elements present between the two members are returned.