[comp.lang.c] Initializing complex structured arrays: HOW?

gwing@mullauna.cs.mu.OZ.AU (Geoff C Wing) (06/30/91)

How can one initialize an array of structures if the structure is not simple,
in this case containing a union?

/* here's the standard version: */
struct standard_struct
{
	int integer1;
};
struct standard_struct standard[] = { 10, 20, 30, 40 };


/* and here's the desired version */
struct test_struct
{
	union {
		int integer2;
		char letter2;
	} hmmm;
};
struct test_struct test[] = { 10, 'a', 30, 40 };
  |        Geoff C Wing       |         \   _  _ _ _  __
  |gwing@mullauna.cs.mu.oz.au |      //  \  |\/|  |  / __  /\
  |gwing@munmurra.cs.mu.oz.au |    \X/ /\ \ |  | _|_ \__| //\\
  |static@phoenix.pub.uu.oz.au| 

steve@taumet.com (Stephen Clamage) (06/30/91)

gwing@mullauna.cs.mu.OZ.AU (Geoff C Wing) writes:

>How can one initialize an array of structures if the structure is not simple,
>in this case containing a union?

>struct test_struct {	/* slightly modified */
>	union {
>		int integer2;
>		char letter2;
>	} u;		/* identifier required */
>} test[] = { 10, 'a', 30, 40 };

In ANSI C, you may initialize a union type via its first member only.
In K&R C, you may not initialize a union type, and a K&R compiler will
reject this code.

The initializers as shown are not fully-bracketed, which yields warnings
from some compilers.  Maintenance is eased with full brackets, which in
this case would look like this:
 ... } test[] = { {10}, {'a'}, {30}, {40} };

With an ANSI compiler, the u.integer2 field of each array member is
initialized to the values 10, 'a', 30, and 40, respectively.  The expression
test[1].u.letter2 will have either the value 'a' or '\0', since it depends on
whether the byte in integer2 at the lowest address contains the
least-significant bits of the value.  (This varies from system to system.)

If you wish to initialize different fields of the union for different
array members, you cannot do it.  You can do it only with run-time
assignments (which are required for K&R compilers anyway).
-- 

Steve Clamage, TauMetric Corp, steve@taumet.com