Reputation: 4543
I have some simple question, when I do something like that:
int* ptr1
int* ptr2
if(ptr1 == ptr2)...
What do I actually compare:
1. addresses where ptr1 and ptr2 saved
2. addresses where content of pointers saved
If there is 1, how can I check 2?
Upvotes: 0
Views: 210
Reputation: 123
Any time you use have something in the form "a==b" you are comparing the contents of variable a to the contents of variable b. In the case that a and b are pointers, their contents are the addresses of some data so a==b will return true if they point to the same location and false otherwise.
To compare the addresses of two variables you need to do &a==&b.
Upvotes: 0
Reputation: 86411
That compares the pointer values, which are addresses.
So ptr1==ptr2
tests whether the two pointers point to the same address -- your #2.
You could express #1 -- comparing the addresses of the pointers themselves -- with &ptr1 == &ptr2
, but here you know that that will be false.
Upvotes: 5
Reputation: 5005
To compare the values pointed to by the pointers:
if (*ptr1 == *ptr2)
To compare the addresses where the pointers are stored use:
if ( &ptr1 == &ptr2 ) since these are the addresses of the pointers.
Upvotes: 0
Reputation: 45948
2) the values of the pointers and therefore the addresses they point to.
Upvotes: 0
Reputation: 39480
When you declare
int *ptr1;
you're defining a variable (that has an address) that points to an integer. You can get the address of that variable by taking the address (&) of that variable, that is,
&ptr1
fundamentally, ptr1 will contain the address of a memory location (where an integer may be stored, if it point to a location where space has been allocated for such a thing).
Comparing the values of the ptr1 and ptr2 variables will tell you if they point at the same variable; comparing the dereferenced values of the ptr1 and ptr2 variables will tell you if the values they point at are the same.
Upvotes: 0
Reputation: 45662
To compare what the pointers actually point towards, use:
if(*ptr1 == *ptr2)...
Upvotes: 0
Reputation: 1054
You compare the actual pointers.
I am not sure from your phrasing what you actually want to do, but it is probably one of:
if (*ptr1 == *ptr2) ...
or
if (&ptr1 == &ptr2) ...
Upvotes: 0
Reputation: 37945
You are comparing wether ptr1 points to the same address as ptr2 does (and reciprocally). That means, your option 2.
Upvotes: 2