Need help with union trick: summary of replies

J. Eric Townsend jet at karazm.math.uh.edu
Sat Jan 5 06:26:45 AEST 1991



I received many replies, some using #defines, others requiring other
changes.  I think the following message best summaraizes the answers that
work the best.

|From: timr at gssc.gss.com (Tim Roberts)
|
|I can think of two ways to solve your array aliasing problem.
|
|1. Ugly Union or Unnamed Structure.
|
|  typedef union pointstruct {
|      struct {
|	  double x, y, z;
|      } p;
|      double foo [3];
|  } Point;
|
|  Point a;
|
|Then  a.p.y == a.foo[1]  .  This is ugly because of the extra name required
|(that is, the "p").  However, this problem is solved in ANSI C by "anonymous
|structures", so if you're using ANSI C you can say:
|
|  typedef union pointstruct {
|      struct {
|	  double x, y, z;
|      };
|      double foo [3];
|  } Point;
|
|  Point a;
|
|Then  a.y == a.foo[1].  This is the best solution, if you have an ANSI 
|compiler.
|
|2. Raw Cast.
|
|typedef struct pointstruct {
|    double x, y, z;
|} Point;
|
|Point a;
|
|Now you can cast a pointer to a into a pointer to double and say something like:
|
|    a.y == ((double *)&a)[0]
|
|Hope this helps.
|-- 
|timr at gssc.gss.com	Tim N Roberts, CCP	Graphic Software Systems
|						Beaverton, OR
--
J. Eric Townsend     Internet: jet at uh.edu    Bitnet: jet at UHOU
Systems Mangler - UH Dept. of Mathematics - (713) 749-2120
"I don't know that atheists should be considered citizens ... or patriots.
This is `one nation under God'." -- President George Bush to an AA reporter.



More information about the Comp.lang.c mailing list