anjruu
anjruu

Reputation: 1264

Can a struct of doubles be typecast to an array of doubles in C?

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

Answers (2)

David Heffernan
David Heffernan

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

Carl Norum
Carl Norum

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

Related Questions