c语言结构体元素遍历方法,有没有办法在C中循环使用不同类型元素的结构体?...

该博客介绍了一种利用C语言预处理器X-Macros来迭代结构体所有字段的方法,通过定义结构体和宏,可以方便地遍历和打印每个字段的值,适用于需要对结构体进行操作的场景。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

我不知道你想要实现什么,但是您可以使用

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中添加要调用的函数的名称…

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值