5

in C++ if I define a structure like this

struct ComplexFloat {
  float r;
  float i;
};

and I declare two variables like this

struct ComplexFloat cf;
float *f=(float*)cf;

can I safely assume that the following condition will always be true

(&(cf.r)==&(f[0]) && &(cf.i)==&(f[1]))

?

In other words, can I safely assume that in a struct containing floats, its elements will occupy contiguous positions in memory and will be ordered according to the order in which they appear in the definition of the struct?

I tested and it is the case with gcc 4.8.2 on Ubuntu, I just want to make sure it is always valid.

oromoiluig
  • 119
  • 1
  • 9

1 Answers1

2

No you cannot assume that i will be in the right place unless you control the alignment of data in the struct. There might be alignment padding between r and i

pm100
  • 42,706
  • 22
  • 76
  • 135