Regardless of the system this code is compiled or executed on, will the fields in the anonymous struct always line up with the indexes in colorChannels?
Not necessarily. The implementation can add byte "padding" between individual variables of the struct
. "Padding" is just additional bytes of memory inserted into the memory definition between variables of or at the end of the struct
in an implementation-defined way. If this happened, then your integer array would not be aligned with the memory layout of the struct
(unless the padding was only at the end of the struct
, maybe). The order of the variables in the struct
in memory should be consistent across implementations (in that variable a
will be followed by b
followed by c
in memory), but, again, the byte padding between can still be there (e.g., a
is followed by b
in memory but there is padding between a
and b
such that they are not right after each other in memory).
For some compilers like gcc, there are ways to modify how it handles padding. This could help guarantee the struct
would be in memory alignment with your integer array, but this could cause other memory problems downstream.
In other words, does the specification require the memory address of myColor.colorChannels[0] to be the same as the address of myColor.red?
If there is no padding between red
, green
, and blue
of the struct
, then the indexes of colorChannels
would match up with each variable in memory.