Need help with union trick
Dan Bernstein
brnstnd at kramden.acf.nyu.edu
Thu Jan 3 13:07:47 AEST 1991
In article <1991Jan3.005700.20623 at lavaca.uh.edu> jet at karazm.math.uh.edu ("J. Eric Townsend") writes:
> I don't think this is possible in C (K&R or ANSI), but maybe someone
> can enlighten me as to the hows and whys of why it is/isnt' possible.
> I have a body of code with the following structure:
> typedef struct pointstruct {
> double x,y,z;
> } Point;
> I would like to be able to reference the elements as an array without
> having to rewrite the existing code. (We've got code to be pasted in that
> relies on being able to grab the x, y and z as array indicies. Grr. :-)
Well, the structure doesn't guarantee array alignment, so your basic
declaration has to be an array. Hence:
typedef struct pointstruct
{
double a[3];
}
Point;
#define x a[0]
#define y a[1]
#define z a[2]
This puts x, y, and z into the main namespace, and it may not be fully
efficient on some machines. If I were desperate I might try
typedef struct pointstruct
{
double x; double y; double z;
}
Point;
typedef union pointunion
{
struct pointstruct p;
double a[3];
}
PU;
I seem to remember from previous discussions that (PU *) &p may not be
aligned correctly, where p has type Point. But if ((PU *) &p).a[0] has
the same address as p.x, ...a[1] as p.y, and ...a[2] as p.z, then you're
going to be safe in practice. If you think your CPU is going to blow up
when you try to compare &(((PU *) &p).a[0]) with &(p.x), don't use this
method.
---Dan
More information about the Comp.lang.c
mailing list