Access struct members as if they are a single array?

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

    If all members a guaranteed to be of type int you can use a pointer to int and increment it:

    int *value = &(values.v_move);
    int *quantity = &(quantities.qtt_move);
    int i;
    average = 0;
    // although it should work, a good practice many times IMHO is to add a null as the last member in struct and change the condition to quantity[i] != null.
    for (i = 0; i < sizeof(quantities) / sizeof(*quantity); i++)
        average += values[i] * quantity[i];
    

    (Since the order of members in a struct is guaranteed to be as declared)

提交回复
热议问题