Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ struct memory allocation [duplicate]

Tags:

c++

memory

struct

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.

like image 500
oromoiluig Avatar asked Oct 31 '22 01:10

oromoiluig


1 Answers

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

like image 118
pm100 Avatar answered Nov 12 '22 20:11

pm100