数组大小取决于结构体字段的 sizeof()
我有一个全局包含文件,其中包含一组结构。在我的程序中的某个位置,我有一个包含成员数组的类。该数组中的元素数量取决于特定结构中特定字段的大小。我想这样做,以便如果结构字段的大小发生更改,数组大小将自动更新。我已经能够使用以下表达式成功完成此操作:
bool shadowChkBox[sizeof(FSCconfigType::WriteEn)*8*MAX_FSCS];
FSCconfigType 是结构类型,WriteEn 是字段之一。现在这可以工作,但只能在 ubuntu 上。在 RHEL 5 上,编译器将其声明为错误。我还有什么其他选择可以做到这一点?我正在使用 Qt。
I have a global include file which contains a set of structures. Somewhere in my program, I have a class that contains a member array. The number of elements in this array is dependent on the size of a specific field in a specific struct. I want to make it so that the array size will get automatically updated if the sizeof the structure field is changed. I have been able to do this succesfully with the following expression:
bool shadowChkBox[sizeof(FSCconfigType::WriteEn)*8*MAX_FSCS];
FSCconfigType is the struct type and WriteEn is one of the fields. Now this worked but only on ubuntu. On RHEL 5, the compiler declared it as an error. What other alternatives could I have for doing this? I am working with Qt.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
这是一个可能的答案:
Here is one possible answer:
一个脆弱的答案是取 WriteEn 和下一个字段的 offsetof 值的差异(或者失败,则取整个结构的大小)。
由于基于对齐的填充,这可能会给出比 sizeof 稍大的答案。
一个更大的问题是,如果你重新安排你的字段而不解决这个问题,会发生什么——但如果你绝望的话,这可能是一个选择。
One fragile answer is to take the difference of the offsetof values for WriteEn and the next field up (or failing that, the sizeof the whole struct).
This may give a slightly larger answer than sizeof due to alignment-based padding.
A bigger problem is what happens if you rearrange your fields without fixing this - but it might be an option if you're desperate.