Access struct members as if they are a single array?

后端 未结 6 1186
花落未央
花落未央 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

    Writing the question came to my mind... Can a union do the job? Is there another clever way to automatize the task of adding another member?

    Yes, a union can certainly do the job:

    union
    {
      values v;    /* As defined by OP */
      int array[6];
    } u;
    

    You can use a pointer to u.values in your API, and work with u.array in your code.

    Personally, I think that all the other answers break the rule of least surprise. When I see a plain struct definition, I assume that the structure will be access using normal access methods. With a union, it's clear that the application will access it in special ways, which prompts me to pay extra attention to the code.

提交回复
热议问题