Die*_*Epp 18
你可以使用联盟.
struct mystruct_s {
... /* who knows how long */
};
typedef union {
struct mystruct_s s;
unsigned char padding[512];
} mystruct;
Run Code Online (Sandbox Code Playgroud)
这将确保联合为512字节或更多.然后,您可以在代码中的某处使用静态断言确保它不超过512个字节:
/* Causes a compiler error if sizeof(mystruct) != 512 */
char array[sizeof(mystruct) != 512 ? -1 : 1];
Run Code Online (Sandbox Code Playgroud)
如果您使用的是C11,则可以采用更好的方法.我还不认识任何使用C11的人.该标准于几周前发布.
_Static_assert(sizeof(mystruct) == 512, "mystruct must be 512 bytes");
Run Code Online (Sandbox Code Playgroud)
请注意,使用零填充的唯一方法是手动(calloc或memset)放置零.编译器忽略填充字节.