C subtracting pointers



In the previous chapter we have learnt about subtracting the integer value from the pointer variable. In this chapter we will be computing the difference between two pointer variables.

Differencing Pointer in C Programming Language :

  1. Differencing Means Subtracting two Pointers.
  2. Subtraction gives the Total number of objects between them .
  3. Subtraction indicates “How apart the two Pointers are ?”

C Program to Compute Difference Between Pointers :

#include<stdio.h>

int main()
{
int num , *ptr1 ,*ptr2 ;

ptr1 = &num ;
ptr2 = ptr1 + 2 ;

printf("%d",ptr2 - ptr1);

return(0);
}

Output :

 2
  • ptr1 stores the address of Variable num
  • Value of ptr2 is incremented by 4 bytes
  • Differencing two Pointers

Important Observations :

Suppose the Address of Variable num = 1000.

Statement Value of Ptr1 Value of Ptr2
int num , *ptr1 ,*ptr2 ;
Garbage Garbage
ptr1 = &num ;
1000 Garbage
ptr2 = ptr1 + 2 ;
1000 1004
ptr2 - ptr1
1000 1004

Computation of Ptr2 – Ptr1 :

Remember the following formula while computing the difference between two pointers –

Final Result  = (ptr2 - ptr1) / Size of Data Type

Step 1 : Compute Mathematical Difference (Numerical Difference)

ptr2 - ptr1  = Value of Ptr2 - Value of Ptr1
             = 1004 - 1000
             = 4

Step 2 : Finding Actual Difference (Technical Difference)

Final Result = 4 / Size of Integer
             = 4 / 2
             = 2
  1. Numerically Subtraction ( ptr2-ptr1 ) differs by 4
  2. As both are Integers they are numerically Differed by 4 and Technically by 2 objects
  3. Suppose Both pointers of float the they will be differed numerically by 8 and Technically by 2 objects

Consider the below statement and refer the following table –

int num = ptr2 - ptr1;

and

If Two Pointers are of Following Data Type Numerical Difference Technical Difference
Integer 2 1
Float 4 1
Character 1 1

In the next chapter we will be Comparing two pointer variables in C Programming.