C/C++: Pointer Arithmetic

Viewed 17483

I was reading a bit in Pointer Arithmetic, and I came upon 2 things I couldn't understand neither know it's use

address_expression - address_expression

and also

address_expression > address_expression

Can someone please explain them to me, how do they work and when they are used.

Edit:

What I meant to say is what do they produce if I just take two addresses and subtract them

And If I take two addresses and compare them what is the result or comparing based upon

Edit: I now understand the result of subtracting addresses, but comparing addresses I still don't get it.

I understand that 1<2, but how is an address greater than another one and what are they compared upon

7 Answers

An analogy I like to use when explaining pointer arithmetic — both how it works, and its limitations — is to think about street addresses.

Suppose there are a bunch of houses on same-sized lots on Elm Street, with all the lots, say, 50 feet wide. Suppose I want to know how far it is from #12 Elm Street to #46 Elm Street, and suppose I want to know this distance as a number of houses, not a distance in feet. Well, obviously, I can just subtract 12 from 46, and get an answer of 34 houses. (Actually, of course, it's a little more complicated than that, because there are probably houses on both sides of the street, but let's ignore that issue for now.)

And suppose over on 10th Avenue there are a bunch of industrial buildings on bigger lots, all 100 feet wide. I can still subtract street numbers, and I'll get distances in number of buildings (not feet).

And this is analogous to pointer subtraction in C, where you get differences that are scaled by the size of the pointed-to objects. You do not get answers as raw bytes (analogous to feet in the street address analogy).

But the other thing the street address analogy helps us understand is why we can't use pointer arithmetic to work with pointers into different arrays. Suppose I want to know how far it is from #12 Elm Street to #30 10th Avenue. Subtracting the addresses doesn't work! It's meaningless. You can't meaningfully subtract or compare addresses on different streets, just as you can't meaningfully subtract or compare pointers into different arrays.

Related