What you do does not violate strict aliasing rules because you cast to/from a char
type pointer. In the standard, pointers to char
types are the only exception from the strict aliasing rules.
As others have pointed out, you can run into the problem of alignment when you cast a char*
to a larger type. You can either work around this by doing the alignment yourself, or just use memcpy()
as Mankarse suggests.
But even the memcpy()
approach is subject to byte order problems: If you've written your program on a little endian machine (x86 for example), it will likely crash on a big endian machine (ARM for example), and vice versa.
So, if you want to write portable code, you need to use a byte order that you specify. You can easily do so using the bit shift operators:
int32_t read_word_le(signed char* bytes) {
return (int32_t)bytes[0] +
((int32_t)bytes[1] << 8) +
((int32_t)bytes[2] << 16) +
((int32_t)bytes[3] << 24);
}
int32_t read_word_be(signed char* bytes) {
return (int32_t)bytes[3] +
((int32_t)bytes[2] << 8) +
((int32_t)bytes[1] << 16) +
((int32_t)bytes[0] << 24);
}