Pointer-to-array overlapping end of array

前端 未结 6 891
花落未央
花落未央 2020-12-31 00:43

Is this code correct?

int arr[2];

int (*ptr)[2] = (int (*)[2]) &arr[1];

ptr[0][0] = 0;

Obviously ptr[0][1] would be inva

6条回答
  •  余生分开走
    2020-12-31 01:05

    Yes, this is correct code. Quoting N4140 for C++14:

    [expr.sub]/1 ... The expression E1[E2] is identical (by definition) to *((E1)+(E2))

    [expr.add]/5 ... If both the pointer operand and the result point to elements of the same array object, or one past the last element of the array object, the evaluation shall not produce an overflow; otherwise, the behavior is undefined.

    There is no overflow here. &*(*(ptr)) == &ptr[0][0] == &arr[1].

    For C11 (N1570) the rules are the same. §6.5.2.1 and §6.5.6

提交回复
热议问题