Reputation: 5761
In my program I'm using constructions like:
typedef struct R{
float s1;
float s2;
float s3;
}Rtype;
and then:
typedef struct Z{
Rtype rval[8][8];
}Ztype;
What am I trying to do next is to recover 3 2-dimensional tables of floats and use them separately. To do that I use:
Ztype* b;
float f[8][8];
for(int i = 0; i < 8; i++)
for(int j = 0; j < 8; j++)
if(mask == 0)
f[i][j] = b->rval[i][j].s1;
else if(mask ==1)
f[i][j] = b->rval[i][j].s2;
else
f[i][j] = b->rval[i][j].s3;
But I think that there should be a way to do it better. So my question is: how can I do that?
Upvotes: 0
Views: 142
Reputation: 61
Use macro replacement or a pointer to one-D array like this:
Rtype (* pRval)[8] = b->rval;
// ...
f[i][j] = pRval[i][j].si;
Seems a little better :).
Upvotes: 0
Reputation: 399881
There are several ways, here are the first that crossed my mind:
mask
once, and pick a different loop that just does the right thing, assuming mask
never changes in the loop.mask
once and compute a pointer offset from the base of each rval
, and use that to copy the float. The assignment would become something like f[i][j] = *(float *) ((char *) b.rval[i][j] + offset);
which looks scary but should compile into something decent.union
to overlay an array with the s1
, s2
and s3
fields, so you can do f[i][j] = b.rval[i][j].u.array[mask];
or something like that.mask
once and set a function pointer to the proper assignment function. This might be expensive if function calls are expensive, though.I'd probably go with the first or second.
Upvotes: 1