Iterating over same type struct members in C

后端 未结 7 601
醉酒成梦
醉酒成梦 2020-12-10 20:06

Is it possible to iterate of a C struct, where all members are of same type, using a pointer. Here\'s some sample code that does not compile:

#include 

        
7条回答
  •  孤街浪徒
    2020-12-10 20:32

    Here's another approach; I've never had reason to do this, but it has the advantage of not mucking up the struct definition. Create a an array of pointers to the members you're interested in, and then iterate over that array:

    typedef struct { int mem1; int mem2; int mem3, int mem4; } foo;
    ...
    foo theStruct;
    int *structMembers[4] = { &theStruct.mem1, &theStruct.mem2, 
                              &theStruct.mem3, &theStruct.mem4};
    ...
    for (i = 0; i < 4; i++)
    {
      printf("%d\n", *structMembers[i]);
    }
    

    This way you don't have to worry about alignment issues biting you, and you can arbitrarily order how you want to iterate over the members (e.g., you could order it so the walk is "mem4, mem3, mem2, mem1").

提交回复
热议问题