Ranter
Join devRant
Do all the things like
++ or -- rants, post your own rants, comment on others' rants and build your customized dev avatar
Sign Up
Pipeless API
From the creators of devRant, Pipeless lets you power real-time personalized recommendations and activity feeds using a simple API
Learn More
Comments
-
jaread2147yIt should work, probably - the memory layout of Model and ModelA (up to the first 4 or 8 bytes (the size of a pointer)) should be the same. A good idea? probably not.
-
lo98be6187yWell, there shouldn't be any problem
Unless you try to use "value" before re-initialization
And it could give bigger problems if ma was an array since ma is a pointer and so is m. ma+1 has a size and m a different one which means overwriting stuff over and over
It really isn't the best idea unless you really know what you're doing
I wouldn't feel comfortable with a bomb like that -
gblues6187y"legal" is very loosely defined in C. This technique is basically a poor man's interface. The important thing is that the members have to be in the same order and the same types.
-
That's legalish (hey, I guess it works), but I think that falls into the category of "Don't ever do this in production." I'm not positive if that falls into the category of undefined behavior, but I wouldn't be shocked if cranking the optimizations up on the compiler broke that
-
lo98be6187yI just realized I didn't answer your question @cpp0xc0ffeeee
It's perfectly legal, meaning it compiles correctly
It won't work unless it's handled veery carefully
And it's also unlikely to crash, meaning it will probably disrupt a shit ton of data before being corrected
Avoid or refactor it, that's what I'd do
Related Rants
Just found this in a C lib:
struct Model
{
char* name;
};
struct ModelA
{
char* name;
int value;
...
};
ModelA* ma=...
...
Model* m=(Model*)ma; //!!?
is it legal?
undefined
struct
pointer
c