Access struct members as if they are a single array?

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

    this problem is common, and has been solved in many ways in the past. None of them is completely safe or clean. It depends on your particuar application. Here's a list of possible solutions:

    1) You can redefine your structures so fields become array elements, and use macros to map each particular element as if it was a structure field. E.g:

    struct values { varray[6]; };
    #define v_read varray[1]
    

    The disadvantage of this approach is that most debuggers don't understand macros. Another problem is that in theory a compiler could choose a different alignment for the original structure and the redefined one, so the binary compatibility is not guaranted.

    2) Count on the compiler's behaviour and treat all the fields as it they were array fields (oops, while I was writing this, someone else wrote the same - +1 for him)

    3) create a static array of element offsets (initialized at startup) and use them to "map" the elements. It's quite tricky, and not so fast, but has the advantage that it's independent of the actual disposition of the field in the structure. Example (incomplete, just for clarification):

    int positions[10];
    position[0] = ((char *)(&((values*)NULL)->v_move)-(char *)NULL);
    position[1] = ((char *)(&((values*)NULL)->v_read)-(char *)NULL);
    //...
    values *v = ...;
    int vread;
    vread = *(int *)(((char *)v)+position[1]);
    

    Ok, not at all simple. Macros like "offsetof" may help in this case.

提交回复
热议问题