Can a double structure be applied to an twin array 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 this is legal, or if different layouts can cause UB.

+4
source share
2 answers

This leads to undefined behavior. The layout of the structure does not fully comply with the standard. For example, there may be a filling.

+5
source

The compiler is allowed to stuff / pack the structure, but like it, so, strictly speaking, your code is not 100% safe. However, it will work on most implementations.

+4
source

Source: https://habr.com/ru/post/1545290/


All Articles