Problem initializing a structure

Chris Torek chris at mimsy.UUCP
Sun Dec 18 01:59:16 AEST 1988


[Quoted text below is slightly edited]

In article <154 at cjsa.WA.COM> jeff at cjsa.WA.COM (Jeffery Small) writes:
>static char *menu[] = { "aaa", "bbb", "ccc", 0 };
>typedef struct {
>	char  **mptr;
>	char  *item;
>} TEST;
>TEST X = { menu, 0 };

>Now, what I actually want to do is to assign [menu[0]] to X.item in the 
>initialization statement ....
>TEST X = { menu, *menu };
>	-- or --
>TEST X = { menu, menu[0] };
>but when I attempt to compile this I get:
>>	"z.c", line 10: illegal initialization

The value for an initialiser must be a constant.  (Actually, it can be
a sort of `extended' constant, including addresses of statically
allocated variables.)  The name of an array is such a constant, as is a
double-quoted string.  The contents of any variable---even if the
contents of that variable is known to be unchanging---is not such a
constant.

One option is to use

	TEST X = { menu, "aaa" };

but this is probably not satisfactory, as it may generate two copies
of the string {'a', 'a', 'a', '\0'}, so that the comparison

	menu[0] == X.item

will be false (0).  (But, depending on your compiler, it may be true,
or 1.)

The other option is guaranteed to work.  Give the `aaa' string a name:

	static char aaa[] = "aaa";
	static char *menu[] = { aaa, "bbb", "ccc", 0 };

	TEST X = { menu, aaa };

Now both menu[0] and X.item are one of these `constants'---the name of
a statically allocated array---and since they are the same constant,
they must have the same value.
-- 
In-Real-Life: Chris Torek, Univ of MD Comp Sci Dept (+1 301 454 7163)
Domain:	chris at mimsy.umd.edu	Path:	uunet!mimsy!chris



More information about the Comp.lang.c mailing list