Initializing arrays of char

Conor P. Cahill cpcahil at virtech.uucp
Sat Oct 6 04:58:47 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 ?

While the "legality" is questionable, so is the "correct" behaviour.

My pcc compiler accepts it, but only takes the first 5 items (of course,
this may not be obvious in a test because of alignment considerations, but
when you use 8 as the dimension and "12345678" as the initializer, you 
will see a problem.

For example:

	char b[8] = "12345678";
	char c[8] = "1234";
	main()
	{
		printf("b = 0x%lx (%s), c = 0x%lx (%s)\n",b,b,c,c);
	}

The output of which is:

	b = 0x400acc (123456781234), c = 0x400ad4 (1234)

Anyway, the compiler *should* complain about it in both cases, but in many
cases will silently do the truncation.

Playing with it a bit more show that both GCC and pcc will complain 
about it if the next byte in the initialization string is not null.

For example:

 char baz[5] = "123456";

will get a warning about the initalizer string being too long (from gcc)
or "non-null byte ignored in string initializer" from pcc.

>I was unable to decrypt what K&R had to say on the matter - should the null
>character appended to the string count as an initializer in both cases ?

No cases should copy the null terminator.  They should not copy any 
more bytes than is specified in the array dimension.  The fact that you
chose a count of 5 will usually result in some alignment bytes between
each variable/structure and hence it appears that the null was copied. 
This is not the case.  Only the first 5 bytes would be copied.

-- 
Conor P. Cahill            (703)430-9247        Virtual Technologies, Inc.,
uunet!virtech!cpcahil                           46030 Manekin Plaza, Suite 160
                                                Sterling, VA 22170 



More information about the Comp.lang.c mailing list