作者热门文章
- c - 在位数组中找到第一个零
- linux - Unix 显示有关匹配两种模式之一的文件的信息
- 正则表达式替换多个文件
- linux - 隐藏来自 xtrace 的命令
我的结构是这样的
typedef struct {
type1 thing;
type2 thing2;
...
typeN thingN;
} my_struct
如何在 while 或 for 等循环中枚举 struct childrens?
最佳答案
我不确定你想要实现什么,但你可以使用 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 中添加要调用的函数的名称...
关于c - 有没有办法在 C 中循环遍历具有不同类型元素的结构?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1784782/
我是一名优秀的程序员,十分优秀!