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

问题描述 投票:19回答:4

我的结构是这样的

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

如何在循环中枚举struct childrens,例如while,或for?

c struct loops
4个回答
41
投票

我不确定你想要实现什么,但你可以使用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_FIELDS中添加要调用的函数的名称...


3
投票

除非结构的确切内容已知,否则没有安全的方法来枚举结构的成员,即使在这种情况下,您也必须小心结构对齐/填充等内容。

根据您的问题,拥有一个struct数组可能更安全。


0
投票

由于您打算在循环中处理它们,我认为不同的类型至少可以被视为相同或具有相似的大小。

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

PS:的确,这不是一个非常安全的做法。这种情况使用OO方法处理得更好,利用多态性。否则,如前所述,无法保证对齐。


0
投票

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

© www.soinside.com 2019 - 2024. All rights reserved.