Ask Your Question

Revision history [back]

click to hide/show revision 1
initial version

To compare two pointers in C, you can directly compare their memory addresses using the comparison operators "<" or ">".

For example:

#include <stdio.h>

int main() {
   int var1 = 5;
   int var2 = 10;
   int *ptr1 = &var1;
   int *ptr2 = &var2;

   if(ptr1 < ptr2) {
      printf("ptr1 is less than ptr2\n");
   } else {
      printf("ptr1 is greater than or equal to ptr2\n");
   }

   return 0;
}

In this example, we declare two integer variables var1 and var2. We also declare two integer pointers ptr1 and ptr2, which are assigned the memory addresses of var1 and var2 respectively using the "&" (address-of) operator. We then use an if/else statement to compare the memory addresses of ptr1 and ptr2, and print a message indicating which pointer has a lower memory address.

Note that this comparison only makes sense when both pointers are pointing to memory locations within the same block of memory. If the pointers are not related to the same data type or free store, the behavior is undefined.