Access struct members as if they are a single array?

后端 未结 6 1174
花落未央
花落未央 2020-11-30 11:43

I have two structures, with values that should compute a pondered average, like this simplified version:

typedef struct
{
  int v_move, v_read, v_suck, v_flu         


        
6条回答
  •  春和景丽
    2020-11-30 12:45

    It really sounds as if this should have been an array since the beggining, with accessor methods or macros enabling you to still use pretty names like move, read, etc. However, as you mentioned, this isn't feasible due to API breakage.

    The two solutions that come to my mind are:

    • Use a compiler specific directive to ensure that your struct is packed (and thus, that casting it to an array is safe)
    • Evil macro black magic.

提交回复
热议问题