C99 -- specifically section 6.2.6.1, paragraph 4 -- states that copying an object representation into an array of unsigned char is allowed:
struct {
int foo;
double bar;
} baz;
unsigned char bytes[sizeof baz];
// Do things with the baz structure.
memcpy(bytes, &baz, sizeof bytes);
// Do things with the bytes array.
My question: can we not avoid the extra memory allocation and copy operation by simply casting? For example:
struct {
int foo;
double bar;
} baz;
unsigned char *bytes = (void *)&baz;
// Do stuff with the baz structure.
// Do things with the bytes array.
Of course, the size would need to be tracked, but is this legal in the first place, or does it fall into the realm of implementation-defined or undefined behavior?
I ask because I'm implementing an algorithm similar to qsort
, and I'd like it to work for any array regardless of type, just as qsort
does.
char
aliases everything, so this should be OK. – Giganticchar
. – Giganticstruct
is a compatible type to the declared type. – Siloum