Search code examples
c++cpointersmathpointer-arithmetic

C/C++: Pointer Arithmetic


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


Solution

  • Pointer subtraction yields the number of array elements between two pointers of the same type.

    For example,

    int buf[10] = /* initializer here */;
    
    &buf[10] - &buf[0];  // yields 10, the difference is 10 elements
    

    Pointer comparison. For example, for the > relational operator: the > operation yields 1 if the pointed array element or structure member on the left hand side is after the pointed array element or structure member on the right hand side and it yields 0 otherwise. Remember arrays and structures are ordered sequences.

     &buf[10] > &buf[0];  // 1, &buf[10] element is after &buf[0] element