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; } |
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:
- Increment/Decrement of a Pointer
- Addition of integer to a pointer
- Subtraction of integer to a pointer
- Subtracting two pointers of the same type
- Comparison of pointers