How To Legally Access Union Array

How To Legally Access Union Array

Suppose I have a type punning union, e.g.

typedef union {
  uint64_t ulong;
  uint32_t uint[2];
} myunion_t;

and I make an array with these as elements. e.g.

myunion_t myarray[3];

If I want to print the last uint, I know I can legally use

printf("%u", myarray[2].uint[1]);

My question is is it legal in c to do it the following way, and if not what rule(s) does it break?

uint32_t *myptr = &myarray[0].uint[0];
printf("%u", myptr[5]);

I suspect it is not legal as the compiler is free to add as much padding to the union as it likes making the uints potentially non-contiguous. However, I'm curious to know what the formal reason is why the latter way is wrong. Thanks.

Answer

According to Read more, the [] subscript operator is defined in such a way that the expression E1[E2] is identical to (*((E1)+(E2))).

According to §6.5.6 ¶8 of C11, when a pointer points to an element of an array and you use the + operator on this pointer, then the result must point to an element of the array, or one past the last element of the array. Otherwise, the behavior is undefined.

Therefore, the behavior is undefined when you use myptr[5].

Enjoyed this article?

Check out more content on our blog or follow us on social media.

Browse more articles