Course contentsShow
← C
Lesson 467 of 1,2197. PointersFree lesson

Pointer comparison with `==` and `<`

Pointer comparison with == and <

What you'll learn: How to compare memory addresses to determine if two pointers point to the same location or to check their relative order in an array.

Since pointers are just variables that hold memory addresses (which are essentially large numbers), we can compare them using standard relational operators. This is incredibly useful when navigating data structures like arrays.

Comparing for Equality (==)

Using the == operator checks if two pointers are pointing at the exact same spot in memory. It doesn't care what data is stored there; it only cares about the address.

Think of it like two GPS devices. If both devices show the coordinates 34.0522° N, 118.2437° W, they are pointing to the same spot (Los Angeles). It doesn't matter if one device is an iPhone and the other is a dedicated Garmin; the destination is identical.

Comparing for Order (<, >, <=, >=)

You can also check if one pointer comes "before" or "after" another. However, this is generally only safe and meaningful when both pointers point to elements within the same array.

Imagine an array as a row of houses on a one-way street. The first house (index 0) has the lowest address, and every house after it has a higher address. If pointer p1 points to the third house and p2 points to the fifth, p1 < p2 will be true because p1 points to an earlier memory location.

Code Example: Finding a Stopping Point

In this example, we use pointer comparison to stop a loop when we reach the end of an array.

#include <stdio.h>

int main() {
    int numbers[] = {10, 20, 30, 40, 50};
    
    int *ptr = &numbers[0];   // Start at the beginning
    int *end = &numbers[5];   // Point just past the last element

    // Use < to stay within bounds
    while (ptr < end) {
        printf("Value: %d\n", *ptr);
        ptr++; // Move to the next address
    }

    // Check for equality
    if (ptr == end) {
        printf("Reached the end of the array.\n");
    }

    return 0;
}

Why this matters

Comparing pointers allows you to set boundaries. By comparing a moving pointer against a "sentinel" or "end" pointer, you can safely process blocks of memory without accidentally wandering into parts of the RAM your program doesn't own.

Key takeaway

Use == to see if two pointers share the same address, and < or > to determine their relative position within the same array.