Pointer and integer expressions

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • randysimes
    New Member
    • Oct 2009
    • 54

    Pointer and integer expressions

    I have a review test question and was wondering why the answers are the way they are. Could someone please explain what you can and cannot do with the following?

    Which of the following expressions are allowed, given that i and j are pointers to the same type and n is an integer?
    n = i / j

    n = j - i correct?

    n = i % j

    n = i + j

    n += j

    j += n correct?

    i = j + n correct?

    *j correct?

    The correct? is what the machine gave me credit for. Why can you do n=j-i and not n=i+j?
  • Banfa
    Recognized Expert Expert
    • Feb 2006
    • 9067

    #2
    You need to look up pointer arithmetic in your reference material.

    However consider the semantic meanings of the expressions given that i and j are memory locations, forget for now that a memory location on many platforms is just an integer offset into memory that is an implementation detail.

    For instance

    n = i - j

    this has the semantic meaning of set n to the difference between memory location i and memory location j that is how many memory locations do I have to move to get from i to j.

    Now ask yourself what would be the semantic meaning of

    n = i + j

    n = i / j

    Can you think of a sensible one?

    Comment

    Working...