I've lost count, long ago, of the number of times I've done something like this in C:
struct foo f;
struct foo* pf = &f;
char* pc = (char*) pf;
transmit(pc, sizeof(f));
Or perhaps:
char* buffer[1024];
receive(buffer, 1024);
float values[256];
for(int ii = 0; ii < 256; ii++) {
float* pf = (float*)(buffer + ii*4);
values[ii] = *pf;
}
Or maybe:
uint32_t ipAddress = ...;
uint8_t* p = (uint8_t*)&ipAddress;
uint8_t octets[4] = {p[0], p[1], p[2], p[3]};
printf("%d.%d.%d.%d\n", octets[0], octets[1], octets[2], octets[3]);
I've only just discovered that reinterpreting a piece of memory like this by casting to another pointer type invokes undefined behaviour. And yet all of the the above examples are meant to do are absolutely necessary. What's the right way of doing them?