Introduction
In C language, pointers can be compared to each other using relational operators, such as greater than, less than, and equal to. This lab will show you how to compare pointers in the C programming language and provide examples for pointers of the same and different types pointing to the same array.
Declare pointer variables
Begin by declaring two pointer variables of the same or different types, depending on the requirements of your program. In this example, we will declare two integer pointers named ptrA and ptrB.
int *ptrA, *ptrB;
Assign memory address to pointer variables
Next, assign a memory address to the pointer variables using the pointer declaration operator (*) and the address of operator (&). This can also be done using a cast, like we have done in these examples.
ptrA = (int *) 1;
ptrB = (int *) 2;
Compare pointer variables
Compare the two pointer variables using one of the relational operators. In this example we use the greater than operator (>). If the condition is true, it will print the statement inside the if block.
if(ptrB > ptrA) {
printf("PtrB is greater than ptrA");
}
Repeat steps for different types of pointers
Repeat steps 1-3 for pointer variables of different types pointing to the same array. In this example, we declare an integer (ptrA) and a float (ptrB) pointer, and assign them memory addresses.
int *ptrA;
float *ptrB;
ptrA = (int *) 1000;
ptrB = (float *) 2000;
Test pointer comparison
Compare the two pointers using a relational operator.
if(ptrB > ptrA) {
printf("PtrB is greater than ptrA");
}
Write code in the main.c file
Write the entire program in the main.c file located in the ~/project/ directory.
#include <stdio.h>
int main() {
int *ptrA, *ptrB;
float *ptrC, *ptrD;
ptrA = (int *) 1;
ptrB = (int *) 2;
ptrC = (float *) 100;
ptrD = (float *) 200;
if (ptrB > ptrA) {
printf("ptrB is greater than ptrA\n");
}
if (ptrD > ptrC) {
printf("ptrD is greater than ptrC\n");
}
return 0;
}
Compile and run the program
Compile the program using a C compiler, such as GCC, and run the program to test the pointer comparison.
Summary
Pointers can be compared to each other using relational operators in C programming. The examples in this lab demonstrate how to compare pointers of the same and different types pointing to the same array. When comparing pointers, be sure they are pointing to the same array for accurate results.



