Typecasting struct to char* for Idiots Like Me

Want to cast from a struct to a character string? Seen all those posts out there suggesting that reinterpret_cast will work, but is unsafe? Yeah, I tried it. Yeah, it’s unsafe.

What about the ones saying you could just malloc()? Well, my own personal mantra says that direct memory manipulation is also rather unsafe if you don’t count right or are not careful with stack memory and such. I have avoided malloc() like I have learned to avoid reinterpret_cast.

But just today I discovered a most elegant solution:

struct newStruct { //33 total bytes long
    int dw0;
    uint_16 s0, s1, s2, s3;
    float f0, f1, f2, f3;
    char b0;
    int i0;
};

void byteOperation(char *p) {
    // Treat input parameter "p" like a big character array and do things one byte at a time!!
}

newStruct v; 
newStruct w[1];

byteOperation((char*)v); // Compiler error: Cannot cast from 'newStruct' to 'char *'
byteOperation((char*)w); // Will just work.

 


Posted

in

,

by

Comments

Leave a Reply

Your email address will not be published. Required fields are marked *