Path: utzoo!mnetor!tmsoft!torsqnt!news-server.csri.toronto.edu!cs.utexas.edu!usc!rutgers!cmcl2!kramden.acf.nyu.edu!brnstnd From: brnstnd@kramden.acf.nyu.edu (Dan Bernstein) Newsgroups: comp.lang.c Subject: Re: Need help with union trick Message-ID: <27454:Jan302:07:4791@kramden.acf.nyu.edu> Date: 3 Jan 91 02:07:47 GMT References: <1991Jan3.005700.20623@lavaca.uh.edu> Organization: IR Lines: 47 In article <1991Jan3.005700.20623@lavaca.uh.edu> jet@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