像访问单个数组一样访问结构成员? [英] Access struct members as if they are a single array?
问题描述
我有两个结构,它们的值应该计算一个经过思考的平均值,就像这个简化版本:
I have two structures, with values that should compute a pondered average, like this simplified version:
typedef struct
{
int v_move, v_read, v_suck, v_flush, v_nop, v_call;
} values;
typedef struct
{
int qtt_move, qtt_read, qtt_suck, qtd_flush, qtd_nop, qtt_call;
} quantities;
然后我用它们来计算:
average = v_move*qtt_move + v_read*qtt_read + v_suck*qtt_suck + v_flush*qtd_flush + v_nop*qtd_nop + v_call*qtt_call;
每时每刻我都需要包含另一个变量.现在,例如,我需要包含 v_clean
和 qtt_clean
.我无法将结构更改为数组:
Every now and them I need to include another variable. Now, for instance, I need to include v_clean
and qtt_clean
. I can't change the structures to arrays:
typedef struct
{
int v[6];
} values;
typedef struct
{
int qtt[6];
} quantities;
这会大大简化我的工作,但它们是需要明确变量名称的 API 的一部分.
That would simplify a lot my work, but they are part of an API that need the variable names to be clear.
所以,我正在寻找一种方法来访问该结构的成员,也许使用 sizeof()
,这样我就可以将它们视为一个数组,但仍然保持 API 不可更改.保证所有值都是int
,但我不能保证int
的大小.
So, I'm looking for a way to access the members of that structures, maybe using sizeof()
, so I can treat them as an array, but still keep the API unchangeable. It is guaranteed that all values are int
, but I can't guarantee the size of an int
.
我想到了写这个问题...union
可以完成这项工作吗?是否有另一种聪明的方法来自动化添加另一个成员的任务?
Writing the question came to my mind... Can a union
do the job? Is there another clever way to automatize the task of adding another member?
谢谢,贝科
推荐答案
如果所有成员 a 都保证是 int
类型,你可以使用指向 int 的指针并递增它:
If all members a guaranteed to be of type int
you can use a pointer to int and increment it:
int *value = &(values.v_move);
int *quantity = &(quantities.qtt_move);
int i;
average = 0;
// although it should work, a good practice many times IMHO is to add a null as the last member in struct and change the condition to quantity[i] != null.
for (i = 0; i < sizeof(quantities) / sizeof(*quantity); i++)
average += values[i] * quantity[i];
(因为结构体中成员的顺序保证和声明的一样)
(Since the order of members in a struct is guaranteed to be as declared)
这篇关于像访问单个数组一样访问结构成员?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!