In a structure, is it legal to use one array field to access another one?

后端 未结 9 463
忘了有多久
忘了有多久 2020-12-24 01:43

As an example, consider the following structure:

struct S {
  int a[4];
  int b[4];
} s;

Would it be legal to write s.a[6] and

9条回答
  •  臣服心动
    2020-12-24 02:36

    Apart from the answer of @rsp (Undefined behavior for an array subscript that is out of range) I can add that it is not legal to access b via a because the C language does not specify how much padding space can be between the end of area allocated for a and the start of b, so even if you can run it on a particular implementation , it is not portable.

    instance of struct:
    +-----------+----------------+-----------+---------------+
    |  array a  |  maybe padding |  array b  | maybe padding |
    +-----------+----------------+-----------+---------------+
    

    The second padding may miss as well as the alignment of struct object is the alignment of a which is the same as the alignment of b but the C language also does not impose the second padding not to be there.

提交回复
热议问题