Subtraction of Two Pointers

The subtraction of two pointers is possible only when they have the same data type. The result is generated by calculating the difference between the addresses of the two pointers and calculating how many bits of data it is according to the pointer data type. The subtraction of two pointers gives the increments between the two pointers. 

For Example: 
Two integer pointers say ptr1(address:1000) and ptr2(address:1004) are subtracted. The difference between addresses is 4 bytes. Since the size of int is 4 bytes, therefore the increment between ptr1 and ptr2 is given by (4/4) = 1.

Example of Subtraction of Two Pointer

Below is the implementation to illustrate the Subtraction of Two Pointers:

C




// C program to illustrate Subtraction
// of two pointers
#include <stdio.h>
 
// Driver Code
int main()
{
    int x = 6; // Integer variable declaration
    int N = 4;
 
    // Pointer declaration
    int *ptr1, *ptr2;
 
    ptr1 = &N; // stores address of N
    ptr2 = &x; // stores address of x
 
    printf(" ptr1 = %u, ptr2 = %u\n", ptr1, ptr2);
    // %p gives an hexa-decimal value,
    // We convert it into an unsigned int value by using %u
 
    // Subtraction of ptr2 and ptr1
    x = ptr1 - ptr2;
 
    // Print x to get the Increment
    // between ptr1 and ptr2
    printf("Subtraction of ptr1 "
           "& ptr2 is %d\n",
           x);
 
    return 0;
}


Output

 ptr1 = 2715594428, ptr2 = 2715594424
Subtraction of ptr1 & ptr2 is 1

Pointer Arithmetics in C with Examples

Pointer Arithmetic is the set of valid arithmetic operations that can be performed on pointers. The pointer variables store the memory address of another variable. It doesn’t store any value. 

Hence, there are only a few operations that are allowed to perform on Pointers in C language. The C pointer arithmetic operations are slightly different from the ones that we generally use for mathematical calculations. These operations are:

  1. Increment/Decrement of a Pointer
  2. Addition of integer to a pointer
  3. Subtraction of integer to a pointer
  4. Subtracting two pointers of the same type
  5. Comparison of pointers

Similar Reads

1. Increment/Decrement of a Pointer

Increment: It is a condition that also comes under addition. When a pointer is incremented, it actually increments by the number equal to the size of the data type for which it is a pointer....

2. Addition of Integer to Pointer

...

3. Subtraction  of Integer to Pointer

When a pointer is added with an integer value, the value is first multiplied by the size of the data type and then added to the pointer....

4. Subtraction of Two Pointers

...

5. Comparison of Pointers

When a pointer is subtracted with an integer value, the value is first multiplied by the size of the data type and then subtracted from the pointer similar to addition....

Pointer Arithmetic on Arrays

...