Excerpt from the book "C++ memory management" by Patrice Roy
For example, the following code is correct, albeit not something one should seek to do (it makes no sense, and it does things in unnecessarily complicated ways, but it’s legal and does no harm):
struct A { int a; short s; }; short * f(A &a) { // pointer interconvertibility in action! int *p = reinterpret_cast<int*>(&a); p++; return reinterpret_cast<short*>(p); // Ok, within the // same object } int main() { A a; short *p = f(a); *p = 3; // fine, technically }
Author does not elaborate this statement. Is it correct from standard point of view and under what condition if so ?
&ain thereinterpret_cast, whenais already a pointer? Should it bereinterpret_cast<int *>(a)?ais a referenceaandsso at best it's implementation defined.intadvanced the address by oneintwhere, baring unusual behaviour, ashortsits. Since the pointed-at object is ashortand will, thanks to thereinterpret_castbe used as ashortit's all good. Unfortunately C++ doesn't guarantee thatswill be immediately afterain memory. For example, how would a 24-bitshortbe aligned after a 32 bitint?shortexisted immediately behind theintin memory (ie, no padding existed), but this code does not guarantee that. The proper way to get a valid pointer to theshortusing pointer arithmetic would be something like this instead:char *p = reinterpret_cast<char*>(&a); p += offsetof(A, s); return reinterpret_cast<short*>(p);