Pointer Subtraction

C Pointer Subtraction

  • Like pointer addition, we can subtract a value from the pointer variable. The formula of subtracting value from pointer variable is given below:
new_address= current_address - (number * size_of(data type))
https://mskuthar.blogspot.com/
Subtraction using pointer

#include <stdio.h>          
void main(){          
int number=50;      
int *p;//pointer to int    
p=&number;//stores the address of number variable               
printf("Address of p variable is %u \n",p);      
p=p-3; //subtracting 3 from pointer variable  
printf("After subtracting 3: Address of p variable is %u \n",p);      


Expected Output
Address of p variable is 3214864300 
After subtracting 3: Address of p variable is 3214864288


  • You can see after subtracting 3 from pointer variable, it is 12 (4*3) less than the previous address value.

#include<stdio.h> 
int main() 

int num , *ptr1 ,*ptr2 ; 
ptr1 = &num ; 
ptr2 = ptr1 + 2 ; 
printf("%d",ptr2 - ptr1); 
return(0); 


Output : 
2

C PROGRAM TO SUBTRACT TWO NUMBERS USING POINTER

#include<stdio.h>
#include<conio.h>
void main()
{
 int num1,num2,sub,*p1,*p2;
 clrscr();
 printf("Enter 1st number: ");
 scanf("%d",&num1);
 printf("Enter 2nd number: ");
 scanf("%d",&num2);
 p1=&num1;
 p2=&num2;
 sub=*p1-*p2;
 printf("\n\nDifference of %d and %d is %d",*p1,*p2,sub);
 getch();
}

Output



Post a Comment

Previous Post Next Post