Qiu
Qiu

Reputation: 5761

Destructing struct

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

Answers (2)

sensor
sensor

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

unwind
unwind

Reputation: 399881

There are several ways, here are the first that crossed my mind:

  1. Inspect the mask once, and pick a different loop that just does the right thing, assuming mask never changes in the loop.
  2. Inspect 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.
  3. Use a 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.
  4. Inspect 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

Related Questions