I have an array, each of which elements can be either uint16_t, or a pair of uint8_t.
Its elements are defined as a union of uint16_t and a submatrix of 2 uint8_t.
Unfortunately, the compiler (MicroChip XC16) allocates twice as much memory as it should for the array.
typedef union { uint16_t u16; // As uint16_t uint8_t u8[2]; // As uint8_t } my_array_t; my_array_t my_array[1]; // 1 word array, for testing my_array[0].u8[0] = 1; my_array[0].u8[1] = 2; uint8_t byte_0 = my_array[0].u8[0]; // Gets 0x01 uint8_t byte_1 = my_array[0].u8[1]; // Gets 0x02 uint16_t byte_0 = my_array[0].u16; // Gets 0x0201
The compiler allocates 4 bytes instead of 2 bytes, as it should be.
Workaround: if I changed the structure to:
typedef union { uint16_t u16;
The compiler allocates 2 bytes properly, but then this is not true:
my_array[0].u8[1] = 2;
although it still works:
uint8_t byte_1 = my_array[0].u8[1];
(except for the inconvenience that the debugger does not show its value).
Question: should I live with a workaround or use the best solution?
Refer to the previous discussion for the above solution.
EDIT.
At the suggestion of EOF (below), I checked sizeof.
To workaround:
sizeof(my_array_t)
After the workaround:
sizeof(my_array_t)
This would mean that it is a compiler error.
source share