力C比结构体尺寸 [英] Force Specific Struct Size in C

查看:116
本文介绍了力C比结构体尺寸的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有关的各种原因,我有一些结构欲强行将特定尺寸(在这种情况下,64字节和512字节)。然而两者,都低于略低于我想他们是大小。

For various reasons, I have some structs I want to force to be specific sizes (in this case 64 bytes and 512 bytes). Both however, are below the somewhat below the sizes I want them to be.

反正我告诉编译器将它们设置为这些特定的尺寸和垫零,否则我将是最好的关闭只是宣称构成了多余的空间结构里的数组,使其对齐的大小我想要什么?

Is there anyway for me to tell the compiler to set them to these specific sizes and pad with zeros, or would I be best off just declaring an array inside the struct that makes up the excess space so that it aligns on the size I want?

推荐答案

您可以使用一个联盟。

struct mystruct_s {
    ... /* who knows how long */
};

typedef union {
    struct mystruct_s s;
    unsigned char padding[512];
} mystruct;

这将确保联合为512个字节以上。然后,您可以确保它在你的code。使用一个静态断言的地方不超过512字节的:

This will ensure the union is 512 bytes or more. Then, you can ensure that it is no more than 512 bytes using a static assertion somewhere in your code:

/* Causes a compiler error if sizeof(mystruct) != 512 */
char array[sizeof(mystruct) != 512 ? -1 : 1];

如果您使用的是C11,有一个更好的方式来做到这一点。我不认识任何人谁使用C11呢。该标准公布星期前的事。

If you are using C11, there is a better way to do this. I don't know anybody who uses C11 yet. The standard was published a matter of weeks ago.

_Static_assert(sizeof(mystruct) == 512, "mystruct must be 512 bytes");

请注意,要与零垫的唯一方法的是手动将零那里(释放calloc memset的)。编译器会忽略填充字节。

Note that the only way to pad with zeroes is to put the zeroes there manually (calloc or memset). The compiler ignores padding bytes.

这篇关于力C比结构体尺寸的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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