+ 3
Can an address be greater or lesser than each other?
Suppose x=3 and y=4,we can easily compare them knowing that y is bigger ,can we compare their address too? Obviously we can't say that address of restaurant is greater than address of school in real life,but what about in terms of programming?? if so then please share the algorithm.
3 Antworten
+ 8
Not bad. This confused me quite a bit. I was thinking along the lines of "those operators won't work on addresses and the compiler would complain', but no. Please refer to this link:
https://stackoverflow.com/questions/9086372/how-to-compare-pointers
It includes how operators work on pointers.
Anyways, I just did a little something to check:
int *p = new int;
int *q = new int;
std::cout << p << " " << q << std::endl;
if (p > q) std::cout << "p is larger.";
else std::cout << "q is larger.";
// From the above, you can see that the hex representation of the memory addresses are compared.
+ 3
Yes. Addresses can be compared just like regular values. Take this as an example:
struct t
{
int a;
int b;
}T;
int main()
{
if (&T.b > &T.a)
std::cout << "B's address is greater than A";
else
{
std::cout << "B's address is not greater than A";
}
}
The address of "b" in this struct will always be greater than "a". That's because in structs and classes, the next address is an offset from the last one in memory. In this case, they are 4 bytes apart because "a" is an int which is 4 bytes long on my system.
+ 1
yes hatsy is right, you could compare them, but why would you want to do that, you can't know where everything is saved, even if it says it is on a greater address, it can be saved somewhere completely else because it is only telling how it is in virtual memory