T* versus char* pointer arithmetic

前端 未结 3 459
灰色年华
灰色年华 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条回答
  •  挽巷
    挽巷 (楼主)
    2021-01-11 15:14

    In [dcl.array]:

    An object of array type contains a contiguously allocated non-empty set of N subobjects of type T.

    Contiguous implies that the offset between any consecutive subobjects of type T is sizeof(T), which implies that the offset of the nth subobject is n*sizeof(T).

    The upper bound of n < N comes from [expr.add]:

    When an expression that has integral type is added to or subtracted from a pointer, the result has the type of the pointer operand. If the expression P points to element x[i] of an array object x with n elements, the expressions P + J and J + P (where J has the value j) point to the (possibly-hypothetical) element x[i + j] if 0 <= i + j < n; otherwise, the behavior is undefined.

提交回复
热议问题