我可以在C ++中安全地将float的结构转换为float数组吗? [英] Can I safely convert struct of floats into float array in C++?

查看:55
本文介绍了我可以在C ++中安全地将float的结构转换为float数组吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

例如,我有这个结构

 结构A {浮动x;浮动y;浮点z;}; 

我可以这样做吗? A a;float * array =(float *)& a; 并使用as浮点数组?

解决方案

从实际意义上讲,是的,您可以这样做,它可以在所有最常用的体系结构和编译器中使用.

请参见> Wikipedia上C结构在X86上的典型对齐" 部分.>

更多详细信息:

  • 浮点数为4个字节,并且不会插入填充(在实际上是所有情况下的 ).

  • 大多数编译器还可以选择指定结构的打包方式,并且您可以强制执行不插入填充的操作(例如,Visual Studio中的#pragma pack)

  • 保证
  • 数组在内存中是连续的.

您可以保证它可以与所有编译器一起在世界上所有CPU上运行吗?不.但是我绝对希望看到一个失败的平台:)

如果存在填充字节,则添加 static_assert(sizeof(A)== 3 * sizeof(float))将使此代码无法编译.因此,您可以确定它在编译时是否有效.

For example I have this struct

struct  A {
    float x;
    float y;
    float z;
};

Can I do this? A a; float* array = (float*)&a; And use a as float array?

解决方案

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.

这篇关于我可以在C ++中安全地将float的结构转换为float数组吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆