I have some simple question, when I do something like that:
int* ptr1
int* ptr2
if(ptr1 == ptr2)...
Wha开发者_如何学Ct 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?
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.
You are comparing wether ptr1 points to the same address as ptr2 does (and reciprocally). That means, your option 2.
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) ...
To compare what the pointers actually point towards, use:
if(*ptr1 == *ptr2)...
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.
2) the values of the pointers and therefore the addresses they point to.
To compare the values pointed to by the pointers:
- check if any of the pointers are NULL
- Figure out what both pointers being NULL means in context
- compare with
if (*ptr1 == *ptr2)
To compare the addresses where the pointers are stored use:
if ( &ptr1 == &ptr2 ) since these are the addresses of the pointers.
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.
精彩评论