Force Specific Struct Size in C

前端 未结 2 1392

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 w

相关标签:
2条回答
  • 2021-01-11 16:42

    You can use a union.

    struct mystruct_s {
        ... /* who knows how long */
    };
    
    typedef union {
        struct mystruct_s s;
        unsigned char padding[512];
    } mystruct;
    

    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];
    

    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");
    

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

    0 讨论(0)
  • 2021-01-11 16:48

    I don't think that there's any way to automatize this, at least in gcc which is the compiler I use. You have to pad your structs.

    Be careful about automatic alignment of variables in your struct. For example struct example{ char a; int b; }

    does not take 5 bytes, but 8.

    0 讨论(0)
提交回复
热议问题