Initializing complex structured arrays: HOW?

Stephen Clamage steve at taumet.com
Mon Jul 1 00:51:50 AEST 1991


gwing at 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 at taumet.com



More information about the Comp.lang.c mailing list