Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Comparing pointer object equality

Dealing with pointers in C (and sometimes C++), I've come to an interesting example:Suppose we have a structure (C structure) as follows:

struct qwe
{
    int someData;
    qwe *ptr;
}

and later some code:

struct qwe d, *p = &d;
p->someData = 1;
p->ptr = p;

I understand that these pointers point to the same object and based on the definition of == in language specification, using this operator as follows:

if (p == p->ptr)
    printf("True\n");

would print True to the console window.Now, this is okay and everything, but these two pointers are not the same objects at all. The question here is about whether there's a way to check for POINTER equality. Now, i know i could do something as create a pointer to these pointers and then compare those new pointers with ==, as follows

struct qwe** pToPtr_1 = &p;
struct qwe** pToPtr_2 = &(p->ptr);
if (pToPtr_1 == pToPtr_2)
    printf("True\n");

,which would produce no output to the console, but i wonder if there's a way to compare pointer addresses directly. I do understand that this would be sort of useless (at least based on my current understandings of C programming language and needs ) but i would still like to know if such feature exists in C (or C++).

like image 490
Transcendental Avatar asked Oct 26 '25 03:10

Transcendental


1 Answers

tl;dr: There is no more "direct" way of doing it; you're already properly comparing the identity of two pointers, using the facilities provided by the language.

What you are asking about is not so much equality as identity. You want to see that two objects are literally in fact the same object, occupying the space in memory, which is distinct from two separate objects with the same value.

As you've said, you can check for the identity of two objects by comparing pointers to them. You're comparing the addresses. When the addresses are the same, it's actually just one object.

The same approach works for the pointers, too, which are themselves just objects. You already wrote the code to do that in your answer:

struct qwe** pToPtr_1 = &p;
struct qwe** pToPtr_2 = &(p->ptr);
if (pToPtr_1 == pToPtr_2)
    printf("True\n");

You can shorten it by avoiding the declarations:

if (&p == &p->ptr)
   printf("True\n");
like image 66
Lightness Races in Orbit Avatar answered Oct 28 '25 17:10

Lightness Races in Orbit



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!