访问结构成员,如果他们是一个单一的阵列? [英] 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;
然后我用它们来计算:
And then I use them to calculate:
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
.
写的问题来到我的脑海......一个联盟
能胜任这项工作?是否有另一种聪明的方式来使自动化添加另一个成员的任务是什么?
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?
谢谢,
贝乔
推荐答案
如果所有成员保证是类型 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屋!