Can I safely convert struct of floats into float array in C++? [duplicate]

In a practical sense, yes you can do that and it will work in all the mostly used architectures and compilers.

See “Typical alignment of C structs on x86” section on Wikipedia.

More details:

  • floats are 4 bytes and no padding will be inserted (in practically all cases).

  • also most compilers have the option to specify the packing of structures and you can enforce that no padding is inserted( i.e. #pragma pack from visual studio )

  • arrays are guarantied to be contiguous in memory.

Can you guarantee that it will work in all CPUs in the world with all the compilers? No.. but I would definitely like to see a platform where this fails 🙂

EDIT: adding static_assert(sizeof(A) == 3*sizeof(float)) will make this code not compile if there are padding bytes. So then you’ll be sure it works when it compiles.

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)