代码之家  ›  专栏  ›  技术社区  ›  drigoSkalWalker

有没有办法在C中循环使用不同类型的元素的结构?

  •  18
  • drigoSkalWalker  · 技术社区  · 16 年前

    我的结构是这样的

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

    如何在while或for之类的循环中枚举struct children?

    4 回复  |  直到 9 年前
        1
  •  44
  •   Haldean Brown    10 年前

    我不确定你想要实现什么,但你可以使用 X-Macros

    //--- first describe the structure, the fields, their types and how to print them
    #define X_FIELDS \
        X(int, field1, "%d") \
        X(int, field2, "%d") \
        X(char, field3, "%c") \
        X(char *, field4, "%s")
    
    //--- define the structure, the X macro will be expanded once per field
    typedef struct {
    #define X(type, name, format) type name;
        X_FIELDS
    #undef X
    } mystruct;
    
    void iterate(mystruct *aStruct)
    {
    //--- "iterate" over all the fields of the structure
    #define X(type, name, format) \
             printf("mystruct.%s is "format"\n", #name, aStruct->name);
    X_FIELDS
    #undef X
    }
    
    //--- demonstrate
    int main(int ac, char**av)
    {
        mystruct a = { 0, 1, 'a', "hello"};
        iterate(&a);
        return 0;
    }
    

    这将打印:

    mystruct.field1 is 0
    mystruct.field2 is 1
    mystruct.field3 is a
    mystruct.field4 is hello
    

    您还可以在X_字段中添加要调用的函数的名称。。。

        2
  •  4
  •   Brian R. Bondy    16 年前

    根据您的问题,使用结构的数组可能更安全。

        3
  •  2
  •   danielkza    16 年前

    如果是这种情况,您的选择将取决于元素的大小。如果它们都是相同的,您可以检索指向该结构的指针,将其转换为您的一个类型,并递增它,直到“用完”整个结构。

    PS:事实上,这不是一种非常安全的做法。使用面向对象的方法,利用多态性,这种情况处理得更好。否则,无法保证前面提到的对齐。

        4
  •  2
  •   AnT stands with Russia    16 年前

    在C语言中,无论结构成员具有相同的大小/类型还是不同的大小/类型,都无法迭代结构成员。