what is pointer past the end of an object means?

后端 未结 3 920
野趣味
野趣味 2021-02-04 20:24

In C++ Primer, Chapter 2, \"Variables and Basic Types\", it says:

it is possible for a pointer to an object and a pointer one past the end of a different

3条回答
  •  鱼传尺愫
    2021-02-04 20:34

    It means that after

    int a[] = { 1, 2 };
    float b;
    

    it's possible that (void *) &a[2] == (void *) &b may compare as true.

    &a[2] (or equivalently, a+2) is a pointer just past the end of a, because the array only contains elements with indices 0 and 1.

    Normally, out-of-range array indices are completely invalid (accessing a[2] is not allowed, nor is even computing &a[3]), but there is a special exception for computing the address just past the end of an array, because as it turned out, that is quite useful, for example when iterating over an array and you need an end value to know when to stop the loop.

提交回复
热议问题