In the last chapter we have studied about the increment operation on pointer variable in this chapter we will study decrement operation on pointer variable.
Formula : ( After decrementing )
new_address = (current address) - i * size_of(data type)
Decrementation of Pointer Variable Depends Upon : data type of the Pointer variable
Example :
Data Type | Older Address stored in pointer | Next Address stored in pointer after incrementing (ptr–) |
---|---|---|
int | 1000 | 0998 |
float | 1000 | 0996 |
char | 1000 | 0999 |
Explanation :
- Decrementing a pointer to an integer data will cause its value to be decremented by 2
- This differs from compiler to compiler as memory required to store integer vary compiler to compiler
Pointer Program : Difference between two integer Pointers
#include<stdio.h> int main(){ float *ptr1=(float *)1000; float *ptr2=(float *)2000; printf("\nDifference : %d",ptr2-ptr1); return 0; }
Output :
Difference : 250
Explanation :
- Ptr1 and Ptr2 are two pointers which holds memory address of Float Variable.
- Ptr2-Ptr1 will gives us number of floating point numbers that can be stored.
ptr2 - ptr1 = (2000 - 1000) / sizeof(float) = 1000 / 4 = 250
Live Example 2:
#include<stdio.h> struct var{ char cvar; int ivar; float fvar; }; int main(){ struct var *ptr1,*ptr2; ptr1 = (struct var *)1000; ptr2 = (struct var *)2000; printf("Difference= %d",ptr2-ptr1); return 0; }
Output :
Difference = 142
Explanation :
ptr2-ptr1 = (2000 - 1000)/Sizeof(struct var)
= 1000 / (1+2+4)
= 1000 / 7
= 142