Is there any way to loop through a struct with elements of different types in C?

后端 未结 4 1742
迷失自我
迷失自我 2020-11-29 21:45

my struct is some like this

typedef struct {
  type1 thing;
  type2 thing2;
  ...
  typeN thingN;
} my_struct 

how to enumerate struct chil

4条回答
  •  予麋鹿
    予麋鹿 (楼主)
    2020-11-29 22:37

    Since you plan to handle them in a loop, I assume the different types can at least be treated alike, or have similar sizes.

    If this is the case, your choice will depend on the size of the elements. If they're all the same, you can retrieve a pointer to the structure, cast it to one of your types, and increment it until you 'used up' the whole structure.

    PS: Indeed, not a very safe practice. This a situation handled much better with an OO approach, taking advantage of polymorphism. Otherwise, there's no guarantees about alignment as previously mentioned.

提交回复
热议问题