Reputation: 1264
Is this legal in C?
struct Doubles
{
double a,b,c;
};
void foo(struct Doubles* bar)
{
double* baz = (double*)bar;
baz[0]++;
baz[1]++;
baz[2]++;
}
I know that it "works" on MSVC 2010, but I don't know if it's legal, or if different layouts could cause UB.
Upvotes: 4
Views: 89
Reputation: 613311
This leads to undefined behaviour. The layout of the struct is not totally prescribed by the standard. For instance, there may be padding.
Upvotes: 5
Reputation: 225072
The compiler is allowed to pad/pack the structure however it likes, so strictly speaking, your code isn't 100% safe. It'll work on most implementations, though.
Upvotes: 4