memory addresses and comparison operators?

It's logical to compare two memory address to see if they are equal or not. It is logical to increment to the next or previous memory address. But does it really make sense to compare whether one memory address is greater than or less than another? What exactly does that imply, the idea of one memory address being greater than another? I ask because I look at this example code from exercise in book:

1
2
3
4
5
6
7
8
long htoi (char s[])

{
    char *p = &s[strlen(s)-1];
    long deci = 0, dig = 0;
    int pos = 0;

    while (p >= s) {


And as you can see s is pointing to the first address of char array. p is pointing to the last address of that char array. And then we enter a while loop which checks the condition if p is greater than or equal to s. Does that make sense? To check if a memory address is greater than another? What does it mean for memory to be greater than?
Memory addresses are stored as integers. Of course, greater memory addresses are simply sequential memory addresses along. This is only useful in arrays (or dodgy random number generators, I guess). In your example, a pointer is being set to point to the last value in the array 's'. If you think about it, another way of declaring the position in an array is to use pointers:
1
2
s[5];     // is the same as
*(s + 5);


So, of course, the last value will be greater than the first value. The idea is to loop until the pointer has gone behind the start of the array, in which case you have iterated over the entire array.
There is no need to even bring in the addresses: you aren't comparing reinterpret_cast<std::uintptr_t>(p), you are comparing p, the pointer.
For two pointers that refer to the elements of the same array (or one past the end) the comparison operators are defined such that the pointer to the element at the greater array index compares greater. Comparing unrelated pointers is a whole other story (it's not necessarily possible or meaningful)

See http://en.cppreference.com/w/cpp/language/operator_comparison#Pointer_comparison_operators
Last edited on
@Cubbi, you know what, now I remember reading this in the book. Yes, your answer reminded me about comparing pointers of the same array.
Topic archived. No new replies allowed.