Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c

casting

struct

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.

like image 579
anjruu Avatar asked Jan 11 '23 09:01

anjruu


1 Answers

This leads to undefined behaviour. The layout of the struct is not totally prescribed by the standard. For instance, there may be padding.

like image 97
David Heffernan Avatar answered Jan 17 '23 05:01

David Heffernan