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; } |
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:
- 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