Does the C standard require the size of an array of n elements to be n times the size of an element?

后端 未结 2 704
离开以前
离开以前 2020-12-09 15:54

Does the C standard require that the size of an array of n elements be n times the size of an element, either by explicit statement or by rigorous logical

2条回答
  •  無奈伤痛
    2020-12-09 16:05

    Yes, it is required that the size of an array T[n] be n * sizeof (T).

    The Standard defines arrays in §6.2.5/20:

    An array type describes a contiguously allocated nonempty set of objects with a particular member object type....

    Further, the sizeof operator yields the total number of bytes in the array(§6.5.3.4/4):

    When sizeof is applied .... to an operand that has array type, the result is the total number of bytes in the array. When applied to an operand that has structure or union type, the result is the total number of bytes in such an object, including internal and trailing padding.

    Since an array consists of a contiguous allocation of objects, there can be no internal padding. And since trailing padding is mentioned explicitly with respect to the sizeof operator only in the context of unions and structures, it seems clear that arrays are expected to possess no such trailing padding.

    Finally, note that in §6.2.6.1/4 is stated:

    Values stored in non-bit-field objects of any other object type consist of n x CHAR_BIT bits, where n is the size of an object of that type, in bytes. The value may be copied into an object of type unsigned char [n] (e.g., by memcpy); the resulting set of bytes is called the object representation of the value.

    Supposing that arrays could have trailing padding bytes, consider an array unsigned char A[n], and further consider the array unsigned char B[sizeof A], to which all of the bytes (including possible padding bytes) of A[] have been copied. Now, A[] must be the same size as B[], since (§6.2.6.1/8):

    Where an operator is applied to a value that has more than one object representation, which object representation is used shall not affect the value of the result.

    This would mean that B[] must have no trailing padding, which would mean that arrays can have trailing padding bytes except under certain special conditions which are nowhere mentioned in the Standard, or alternatively that arrays may have trailing padding except for arrays of unsigned char. Since neither of these possibilities is mentioned in the Standard, it seems reasonable to conclude that arrays must not have trailing padding in the first place.

提交回复
热议问题