Initializing arrays of char

Bill Poser poser at csli.Stanford.EDU
Fri Oct 5 10:53:26 AEST 1990


In article <1990Oct4.152756.6850 at micrognosis.co.uk> nreadwin at micrognosis.co.uk (Neil Readwin) writes:
>
> Can someone tell me why the following initializer is legal inside a 
> structure, but not outside it ? Or is it a compiler bug ?
>
>struct foo {
>	char x[5];
>	} bar = {"12345"};
>
>char baz[5] = "12345";

I would say that both are erroneous. The reason that you can't assign
"12345" to baz is that baz is an array of FIVE chars and the string "12345"
requires SIX characters, five for the five digits, and one for the
terminating null. The largest string (in the sense of "sequence of characters
terminated by a null") that you can put in baz is one four characters long.
For this reason, the structure initialization shouldn't work either.
Padding of the structure may allocate an additional byte so that
the assignment doesn't actually trash anything, but I don't see why the
compiler isn't checking the declared array size.



More information about the Comp.lang.c mailing list