Hairi Hairi - 3 months ago 27
C Question

What happens when I cast uint8_t array to uint32_t?

Suppose I have this array:

uint8_t arr[10];


located at address
0x00
.

Then I want to assign part of it to uint32_t value. Aggregatin of arr[1], arr[2], arr[3] and arr[4] to 32 bit integer. Here is an example:

uint8_t arr[10];
uint32_t i;
i = *( (uint32_t *)&arr[1] );


What bothers me is that
arr[1]
is located at address not multiple of four(at address 0x01). So the question is: what would happen on 32bit platform? Is this legal, does it have some disadvantages compared to standard
uint32
assignments?

Answer

It's illegal, because it breaks strict aliasing rules, resulting in undefined behaviour.

Use memcpy instead:

memcpy(&i, &arr[1], sizeof(i));

But do notice that this code assumes host endianness. If you need endianness independent code, use bit shifting and masking to combine 4 values in to integer, or swap bytes after memcpy (compilers usually offer some kind intrisics for this).

Comments