Ask Your Question
3

How do you contrast two pointers in C?

asked 2022-11-27 11:00:00 +0000

lalupa gravatar image

edit retag flag offensive close merge delete

1 Answer

Sort by ยป oldest newest most voted
1

answered 2022-02-06 14:00:00 +0000

devzero gravatar image

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.

edit flag offensive delete link more

Your Answer

Please start posting anonymously - your entry will be published after you log in or create a new account. This space is reserved only for answers. If you would like to engage in a discussion, please instead post a comment under the question or an answer that you would like to discuss

Add Answer


Question Tools

Stats

Asked: 2022-11-27 11:00:00 +0000

Seen: 15 times

Last updated: Feb 06 '22