Aliasing of multi-dimensional arrays

后端 未结 1 1583
广开言路
广开言路 2020-12-19 20:19

It is well known that a 2D array is an array of arrays, and that it is required by standard to be a contiguously allocated nonempty set of objects (6.2.5 Types §20)

相关标签:
1条回答
  • 2020-12-19 21:06

    Even if the strict aliasing rules allows to access an object of one type from an object containing it, there are two elements in standards to say that aliasing a 2D array to a 1D array of same size is not allowed:

    Compatible type

    6.2.7 Compatible type and composite type

    1 Two types have compatible type if their types are the same.
    ...
    3 A composite type can be constructed from two types that are compatible; it is a type that is compatible with both of the two types and satisfies the following conditions:

    • If one type is an array of known constant size, the composite type is an array of that size; otherwise, if one type is a variable length array, the composite type is that type.
      ...

    These rules apply recursively to the types from which the two types are derived.

    Conformance:

    4 Conformance

    ...

    1. ... Undefined behavior is otherwise indicated in this International Standard by the words ‘‘undefined behavior’’ or by the omission of any explicit definition of behavior. There is no difference in emphasis among these three; they all describe ‘‘behavior that is undefined’’.
    2. A program that is correct in all other aspects, operating on correct data, containing unspecified behavior shall be a correct program and act in accordance with 5.1.2.3.
      ...
    3. A strictly conforming program shall use only those features of the language and library specified in this International Standard.2) It shall not produce output dependent on any unspecified, undefined, or implementation-defined behavior, and shall not exceed any minimum implementation limit.

    My understanding is that aliasing of 2D array with a 1D array is unspecified by the standard and as such leads to undefined behaviour. A program using it is still a correct program that shall be successfuly compiled, but its output is unspecified

    A stricly conforming program should not alias a 2D array to an 1D array.

    That being said, common implementation allows it and process it as expected (which is allowed per undefined behaviour...) in order to not break legacy code that heavily depends on it.

    0 讨论(0)
提交回复
热议问题