Subtraction  of Integer to Pointer

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.

For Example:
Consider the same example as above where the ptr is an integer pointer that stores 1000 as an address. If we subtract integer 5 from it using the expression, ptr = ptr – 5, then, the final address stored in the ptr will be ptr = 1000 – sizeof(int) * 5 = 980.

 

Example of Subtraction of Integer from Pointer

Below is the program to illustrate pointer Subtraction:

C




// C program to illustrate pointer Subtraction
#include <stdio.h>
 
// Driver Code
int main()
{
    // Integer variable
    int N = 4;
 
    // Pointer to an integer
    int *ptr1, *ptr2;
 
    // Pointer stores the address of N
    ptr1 = &N;
    ptr2 = &N;
 
    printf("Pointer ptr2 before Subtraction: ");
    printf("%p \n", ptr2);
 
    // Subtraction of 3 to ptr2
    ptr2 = ptr2 - 3;
    printf("Pointer ptr2 after Subtraction: ");
    printf("%p \n", ptr2);
 
    return 0;
}


Output

Pointer ptr2 before Subtraction: 0x7ffd718ffebc 
Pointer ptr2 after Subtraction: 0x7ffd718ffeb0 

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

...