Initializing arrays of char

Henry Spencer henry at zoo.toronto.edu
Sat Oct 6 03:15:21 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"};

It's a compiler bug.  ANSI C, 3.5.7 (emphasis added):

	An array of character type may be initialized by a character
	string literal, optionally enclosed in braces.  Successive
	characters of the character string literal (including the
	terminating null character *if there is room* or if the array
	is of unknown size) initialize the elements of the array.

Your compilers are assuming that "12345" has six characters in it, which
is correct in general, but for this oddball special case in initializers
the terminating null is present only if there is room for it.
-- 
Imagine life with OS/360 the standard  | Henry Spencer at U of Toronto Zoology
operating system.  Now think about X.  |  henry at zoo.toronto.edu   utzoo!henry



More information about the Comp.lang.c mailing list