C comparing two pointer variables



In the previous chapter we have learnt about computing the difference between two pointer variables, In this chapter we will be learning how two pointers can be compared ?

Comparison between two Pointers :

  1. Pointer comparison is Valid only if the two pointers are Pointing to same array
  2. All Relational Operators can be used for comparing pointers of same type
  3. All Equality and Inequality Operators can be used with all Pointer types
  4. Pointers cannot be Divided or Multiplied

Point 1 : Pointer Comparison

#include<stdio.h>

int main()
{
int *ptr1,*ptr2;

ptr1 = (int *)1000;
ptr2 = (int *)2000;

if(ptr2 > ptr1)
   printf("Ptr2 is far from ptr1");

return(0);
}

Pointer Comparison of Different Data Types :

#include<stdio.h>

int main()
{
int *ptr1;
float *ptr2;

ptr1 = (int *)1000;
ptr2 = (float *)2000;

if(ptr2 > ptr1)
   printf("Ptr2 is far from ptr1");

return(0);
}

Explanation :

  • Two Pointers of different data types can be compared .
  • In the above program we have compared two pointers of different data types.
  • It is perfectly legal in C Programming.

[box]As we know Pointers can store Address of any data type, address of the data type is “Integer” so we can compare address of any two pointers although they are of different data types.[/box]

Following operations on pointers :

> Greater Than
< Less Than
>= Greater Than And Equal To
<= Less Than And Equal To
== Equals
!= Not Equal

Divide and Multiply Operations :

#include<stdio.h>

int main()
{
int *ptr1,*ptr2;

ptr1 = (int *)1000;
ptr2 = ptr1/4;

return(0);
}

Output :

In the next chapter we will be learning different invalid or illegal arithmetic operations performed on the pointer.