Hello, OnlineGDB Q&A section lets you put your programming query to fellow community users. Asking a solution for whole assignment is strictly not allowed. You may ask for help where you are stuck. Try to add as much information as possible so that fellow users can know about your problem statement easily.

How to compare the two pointer in c

+7 votes
asked Mar 4, 2025 by PRIYADHARSHINI G (190 points)

1 Answer

0 votes
answered Mar 5, 2025 by Peter Minarik (101,340 points)
edited Mar 5, 2025 by Peter Minarik

A pointer is ultimately a memory address of another variable.

E.g.

#include <stdio.h>

int main()
{
    double salary = 120000.0;
    double * pSalary = &salary;
    printf("Pointer to (the address of) the salary is: %p\n", pSalary);
    printf("The value stored at %p is %lf\n", pSalary, *pSalary);
    return 0;
}

Being a memory address, it really means, it's an integral number depending on the processor architecture. For a 64-bit system, the pointers are stored in a 64-bit unsigned integral type (uint64_t as defined in cstdint.h).

Now, that we know that a memory address is just an integral number, we can do any arithmetic with memory addresses as we'd do with integral numbers, including comparisons, such as ==, <, <=, >=, >, etc. We can not only compare them but do addition and subtraction as well, as in +1 points to the next element of the same size in memory, based on the size of the variable pointed (double in our case below, where double takes up 8 bytes).

#include <stdio.h>

void Compare(double * address1, double * address2)
{
    if (address1 == address2)
        printf("The two addresses are the same: %p\n", address1);
    else if (address1 < address2)
        printf("%p < %p\n", address1, address2);
    else
        printf("%p > %p\n", address1, address2);
}

int main()
{
    double salaries[] = { 120000.0, 100000.0 };
    double * pSalary0 = &salaries[0];
    double * pSalary1 = &salaries[1];
    double * pSalary2 = salaries;
    double * pSalary3 = salaries + 1; // step to the next element from the pointer of the array
    double * pSalary4 = pSalary0 + 1; // step to the next double after a pointer double
    Compare(pSalary0, pSalary1); // <
    Compare(pSalary0, pSalary2); // ==
    Compare(pSalary1, pSalary3); // ==
    Compare(pSalary3, pSalary4); // ==

    return 0;
}

If this is not what you're after, could you be more specific what you'd like to know?

Welcome to OnlineGDB Q&A, where you can ask questions related to programming and OnlineGDB IDE and receive answers from other members of the community.
...