有什么方法可以在 C 中循环遍历具有不同类型元素的结构? [英] Is there any way to loop through a struct with elements of different types in C?
本文介绍了有什么方法可以在 C 中循环遍历具有不同类型元素的结构?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我的结构有点像这样
typedef struct {
type1 thing;
type2 thing2;
...
typeN thingN;
} my_struct
如何在 while 或 for 等循环中枚举 struct childs?
how to enumerate struct childrens in a loop such as while, or for?
推荐答案
我不确定您想要实现什么,但是您可以使用 X-Macros 并让预处理器对结构的所有字段进行迭代:
I'm not sure what you want to achieve, but you can use X-Macros and have the preprocessor doing the iteration over all the fields of a structure:
//--- 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"
", #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中添加要调用的函数名...
You can also add the name of the function to be invoked in the X_FIELDS...
这篇关于有什么方法可以在 C 中循环遍历具有不同类型元素的结构?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文