Why can't I do this?

Morris Keesan keesan at bbncca.ARPA
Sat Jan 14 08:31:55 AEST 1984

P.T.Withington asks if 

>>  static char *foo[] = {"hello",
>>                        "out",
>>                        "there"};

is legal, why isn't

>>  static int *bar[] = {{0, 1, 2},
>>                       {3, 4},
>>                     {5, 6, 7, 8}};

legal?  First, let's look at the declarations aside from the initialization.
Both identifiers are declared to be arrays of pointers, and as such should be
initialized with pointers.  Note also that initializers must be constants.
"hello" is a genuine constant, representing a pointer to the array
{'h','e','l','l','o','\0'} somewhere in memory.  However, strings are the only
case where an aggregate can be represented as a constant, and that's because
the value is really the address.  {0, 1, 2} is not a constant expression, nor
is it an aggregate or the address of an aggregate -- and the only place the
it can legally appear in a C program is as an initializer.  Note that the
same thing is true of {'h','e','l','l','o','\0'} -- it can only be an

    I hope you realize that foo, above, does not contain any of the characters
represented -- sizeof foo == 3 * sizeof(char *).  If you really want bar to be
an array of pointers also, a way to declare it would be
    static int bar1[] = {0,1,2}, bar2[] = {3,4}, bar3[] = {5,6,7,8};
    static int *bar[] = { bar1, bar2, bar3 };
where bar1, bar2, and bar3 in the initializer for bar are the addresses of the
respective arrays.
					Morris M. Keesan
					keesan @ BBN-UNIX.ARPA

More information about the Comp.lang.c mailing list