C pointer arithmetic

后端 未结 5 1760
夕颜
夕颜 2020-12-05 11:32

Given this code:

int *p, *q;

p = (int *) 1000;
q = (int *) 2000;

What is q - p and how?

5条回答
  •  借酒劲吻你
    2020-12-05 12:17

    It's actually undefined, according to the standard. Pointer arithmetic is not guaranteed to work unless the pointers are both pointing to either an element in, or just beyond, the same array.

    The relevant section of the standard is 6.5.6:9 (n1362 draft of c1x but this hasn't changed since c99) which states:

    When two pointers are subtracted, both shall point to elements of the same array object, or one past the last element of the array object; the result is the difference of the subscripts of the two array elements.

    You'll most likely get 250 if your int datatype is 4 bytes but there's no guarantee. Undefined behaviour (unlike implementation-defined behaviour) means just that, undefined. Anything can happen, up to an including the total destruction of a large proportion of space-time.

    A refresher course:

    • Defined behaviour is what is mandated by the standard. Implementations must do this to be conformant.
    • Implementation-defined behaviour is left up to the implementation but it must document that behaviour clearly. Use this if you don't care too much about portability.
    • Undefined behaviour means anything can happen. Don't ever do that!

提交回复
热议问题