T* versus char* pointer arithmetic

前端 未结 3 488
灰色年华
灰色年华 2021-01-11 14:42

Assume we have an array that contains N elements of type T.

T a[N];

According to the C++14 Standard, under which conditions do we

3条回答
  •  旧时难觅i
    2021-01-11 15:08

    It's always true, but instead of looking at the rules for pointer arithmetic you must rely on the semantics given for the sizeof operator (5.3.3 [expr.sizeof]):

    When applied to a reference or a reference type, the result is the size of the referenced type. When applied to a class, the result is the number of bytes in an object of that class including any padding required for placing objects of that type in an array. The size of a most derived class shall be greater than zero. The result of applying sizeof to a base class subobject is the size of the base class type. When applied to an array, the result is the total number of bytes in the array. This implies that the size of an array of n elements is n times the size of an element.

    It should be clear that there's only one packing that puts n non-overlapping elements in space of n * sizeof(element), namely that they are regularly spaced sizeof (element) bytes apart. And only one ordering is allowed by the pointer comparison rules found under the relational operator section (5.9 [expr.rel]):

    Comparing pointers to objects is defined as follows:

    • If two pointers point to different elements of the same array, or to subobjects thereof, the pointer to the element with the higher subscript compares greater.

提交回复
热议问题