Path: utzoo!utgpu!news-server.csri.toronto.edu!cs.utexas.edu!uunet!virtech!cpcahil From: cpcahil@virtech.uucp (Conor P. Cahill) Newsgroups: comp.lang.c Subject: Re: Initializing arrays of char Message-ID: <1990Oct05.185847.28736@virtech.uucp> Date: 5 Oct 90 18:58:47 GMT References: <1990Oct4.152756.6850@micrognosis.co.uk> Reply-To: cpcahil@virtech.UUCP (Conor P. Cahill) Organization: Virtual Technologies Inc., Sterling VA Lines: 51 In article <1990Oct4.152756.6850@micrognosis.co.uk> nreadwin@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