Interview: Union Memory Representation
In this example, the union a has two members: an integer i and a character array x of size 2. Since both members share the same memory space, the memory layout is as follows:
a.x[0]occupies the low byte of the memory space (address 0)a.x[1]occupies the high byte of the memory space (address 1)
When we assign values to a.x[0] and a.x[1], the resulting memory layout is 0x010A, where 0x0A is the low byte (address 0) and 0x01 is the high byte (address 1). This is known as little-endian byte order.
Struct vs Union Memory Layout
To better understand the difference between struct and union memory layouts, let's compare the two: