what is pointer past the end of an object means?

后端 未结 3 921
野趣味
野趣味 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:59

    Suppose you have an array, int foo[5] = {1,2,3,4,5};. It's laid out in memory like this:

    -----------
    |1|2|3|4|5|
    -----------
    

    It's legal to have a pointer that points to any member of the array; but it's also legal for a pointer to point one past the end of the array (usually to signal that it has reached the end of the array when doing an STL algorithm using iterators) - although it isn't legal to dereference that pointer. Like so:

    -------------
    |1|2|3|4|5|?|
    -------------
     ^         ^
     |         |
     p         q
    

    p is a pointer into the array; q is a pointer one-past-the-end.

    Now, suppose you also have an array const char bar[3] = "Hi";. It's possible that the two arrays have been allocated next to each other in memory, like so:

    <--foo---> <-bar->
    -----------------
    |1|2|3|4|5|H|i|0|
    -----------------
     ^         ^
     |         |
     p         q
    

    Then q is both a one-past-the-end for foo, and also pointing to the physical location for bar[0].

提交回复
热议问题