Iterating over same type struct members in C

后端 未结 7 529
醉酒成梦
醉酒成梦 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:44

    You can also use an unnamed union/struct:

    struct foo {
        union {
            struct {
                int mem1;
                int mem2;
                int mem3;
                int mem4;
            };
            int elements[4];
        };
    };
    
    foo thefoo;
    for (int i = 0; i < 4; ++i) {
        thefoo.elements[i] = i;
    }
    

    This might not work on some compilers, int this case you'll have to explicitily name the union and struct inside foo,

    0 讨论(0)
提交回复
热议问题