# Thread: how to check if two link list nodes are same .. ?

1. ## how to check if two link list nodes are same .. ?

I have two pointers pt1 and pt2 pointing to link list nodes.
I read that two pointers can not be compared (they can be only in case they point to member of same array) , then how do i check that pt1 and pt2 point to the same node or not?

2. If your pointers point to a node, then you can simply compare them. If you have a structure and they point to different fields in your node structure then you know the offset of the field in the structure, so subtract that from each pointer and compare those.
To reiterate:
Code:
```struct Node {
struct Node *next;
int value;
};

/* pointers don't simply point to the node */
struct Node aNode;
int *nodeVal = &aNode.value;
node *nodeNext = &aNode.next;

if ((nodeVal - offsetof(struct aNode, value)) == (nodeNext - offsetof(struct aNode, next))```

3. You can see if pt1 == pt2 in that case.

It sounds like you have an instance of a struct with 2 pointers pointing to the same instance. Comparing pointers this way would not work if they pointed to 2 different instances of the struct and you just wanted to see if both of them had the same data in them.

4. i want to check if pt1 and pt2 point to same instance (data in instances is not relevant to me).....

can i simply do pt1 == pt2
i have read that you can't compare two pointers unless they point to elements of same array.

5. kerninghan ritchie
pg102 last paragraph
"Any pointer can be meainingfully compared for equality or inequality with zero. But the behavior is undefined for arithmetic or comparisons with pointers that do not point to members of the same array."

6. If pt1 and pt2 both point to the same instance you can test them for equality. You're misreading what that exceprt says.

When they said "comparison" they were referring to something like if(pt1 < pt2) which is actually useful in an array, but not really anywhere else. "Comparison" is not the same as "equality or inequality".

Here's something from a little newer reference.

From ISO C99:
6.5.9 Equality operators
Syntax
1 equality-expression:
relational-expression
equality-expression == relational-expression
equality-expression != relational-expression
Constraints
2 One of the following shall hold:
— both operands have arithmetic type;
— both operands are pointers to qualified or unqualified versions of compatible types;
— one operand is a pointer to an object or incomplete type and the other is a pointer to a
qualified or unqualified version of void; or
— one operand is a pointer and the other is a null pointer constant.

7. > can i simply do pt1 == pt2
Yes.

> i have read that you can't compare two pointers unless they point to elements of same array.
That refers to say
Code:
```int arr[10];
if ( &arr[i] < &arr[j] )```
But not this
Code:
```int i, j;
if ( &i < &j ) /* this is meaningless */```

8. Thanks a lot everyone .

-Gaurav