gpt4 book ai didi

c - 如何循环访问结构成员?

转载 作者:行者123 更新时间:2023-12-01 03:32:35 25 4
gpt4 key购买 nike

让我们有一个这样的结构:

struct _Example {
int a;
int b;
int c;
} Example;

一个函数通过指针获取这个结构并输出结构成员的值。我想像这样打印这些值:

Example example;
func(&example);

if(example.a)
printf("%d", example.a);

if(example.b)
printf("%d", example.b);

if(example.c)
printf("%d", example.c);

如何用循环替换那些多个 if 条件?

最佳答案

最好的方法可能是在 union 上使用双关语。它允许您使用具有不同变量表示的相同内存区域,例如通过给每个结构成员单独的名称,同时保持能够循环通过它们。

#include <stdio.h>

typedef union {
struct // anonymous struct, requires standard C compiler
{
int a;
int b;
int c;
};
int array[3];
} Example;


int main (void)
{
Example ex = { .a=1, .b=2, .c=3 };

for(size_t i=0; i<3; i++)
{
printf("%d\n", ex.array[i]);
}
}

如果你不能改变结构定义,那么第二好的是通过字符类型进行一些指针运算。不过,这需要更加小心,这样您就不会最终编写行为定义不明确的代码 - 您需要注意对齐和严格别名之类的事情。如果结构因不同类型的成员而变得更加复杂,则首选使用字符类型,因为字符类型不会出现别名问题。

假设 uint8_t 是字符类型,那么:

#include <stdio.h>
#include <stdint.h>

typedef union {
struct
{
int a;
int b;
int c;
};
} Example;


int main (void)
{
Example ex = { .a=1, .b=2, .c=3 };
uint8_t* begin = (uint8_t*)&ex;
uint8_t* end = begin + sizeof ex;


for(uint8_t* i=begin; i!=end; i+=sizeof(int))
{
printf("%d\n", *(int*)i);
}
}

关于c - 如何循环访问结构成员?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51942867/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com