In the following code -
#include <iostream>
using namespace std;
struct S1{
int a; int b; int c; int d;
};
struct S{
int a; int b;
};
int main() {
S1 obj1;
obj1.a = 1;
obj1.b = 2;
obj1.c = 3;
obj1.d = 4;
cout << obj1.a << " "
<< obj1.b << " "
<< obj1.c << " "
<< obj1.d << "\n";
// more code
auto ptr = reinterpret_cast<S *>(&obj1);
cout << ptr->a << " " << ptr->b << "\n";
// more code
// someFunc(ptr, sizeof(obj1));
}
I'm assigning values to members of structure S1 and then using them somewhere else as struct S pointer by reinterpret_casting the original S1 to S. This works fine.
Now a little ahead, I've a function someFunc(const void *ptr, int len) that takes a const void * pointer and length to the structure being passed. In this case, it is expected to pass S1 structure to it, and inside it it has some memcpy calls to copy the structure and work on that copy. So can I do this? -
// more code
someFunc(ptr, sizeof(obj1));
}
meaning pass that reinterpret_casted pointer to this function and size of original S1 structure or do I have to again reinterpret_cast it back S1 and then pass the pointer again.
Not having to reinterpret_cast again to original type will save me some switch cases for similar types like S1. Note that someFunc can easily find out type based on size passed in because those similar types differ greatly in size.
reinterpret_casthere?S1andSare two different types.S1,S2,S3,S4with Common Initial Sequence matching with typeS. For some library, they all need to be casted to typeSpointer. Then I need to pass them in another function that takesconst void *and length of original type. So is it safe to pass the casted toSpointer and length of original typeS1orS2.. whichever it may be. Here - ideone.com/TIzNS8