#include<stdio.h>
int main() {
int val = 10;
int *ptr = &val;
printf("The value of adress of pointer : %u\n", ptr);
ptr++;
printf("The value of address of pointer after incrementing : %u\n", ptr);
ptr--;
printf("The value of address of pointer after decrementing : %u", ptr);
return 0;
}
Output :
The value of adress of pointer : 2221651772
The value of address of pointer after incrementing : 2221651776
The value of address of pointer after decrementing : 2221651772
What Exactly Happened Above?
ExplanationThe address value of pointer is 2221651772(depends on compiler) , after incrementing it is incremented by 4 as it is a pointer of int data type which size is 4.
#include<stdio.h>#include
int main()
{
int val = 9;
int *ptr = &val;
printf("Value of Pointer before Addition : ");
printf("%p \n", ptr);
ptr = ptr + 5;
printf("Pointer ptr after Addition: ");
printf("%p \n", ptr);
return 0;
}
Output :
Value of Pointer before Addition : 0x7ffe75b09ffc
Pointer ptr after Addition: 0x7ffe75b0a010
Subtracting of two pointers of similar type :
Subtraction of two pointers is only possible, if they have same data type. When two pointers of same data type is subtracted , their value is subtracted then result will be divided by the size of data type.
Example :
In the below program, we explain the subtraction of two pointers of similar data type.
#include<stdio.h>
int main()
{
int val1 = 8, val2 = 6;
int *ptr1, *ptr2;
ptr1 = &val1;
ptr2 = &val2;
printf("Value of adress of ptr1 = %u \n", ptr1);
printf("Value of address of ptr2 = %u \n", ptr2);
val1 = ptr2 - ptr1;
printf("Subtraction is %d\n", val1);
return 0;
}
Output :
Value of adress of ptr1 = 2406668336
Value of address of ptr2 = 2406668340
Subtraction is 1
Comparison of two pointers of similar type :
Comparison of two pointers is only possible, if they have same data type. Two pointers can be compared by the operators >, ==, <= , >=. It returns TRUE if condition valid, otherwise return FALSE.
Example :
In the below program, we explain the comparison of two pointers of similar data type.
#include<stdio.h>#include
int main() {
int val1 = 10, val2 = 5;
int *ptr1=&val1;
int *ptr2=&val2;
if(*ptr1<*ptr2)
{
printf("\n%d less than %d",*ptr2,*ptr1);
}
else if(*ptr2<*ptr1)
{
printf("\n%d greater than %d",*ptr1,*ptr2);
}
else{
printf("Both values are equal");
}
return 0;
}
Output :
10 greater than 5
Prime Course Trailer
Related Banners
Get PrepInsta Prime & get Access to all 200+ courses offered by PrepInsta in One Subscription
Login/Signup to comment