Path: utzoo!attcan!uunet!aplcen!haven!mimsy!chris From: chris@mimsy.umd.edu (Chris Torek) Newsgroups: comp.lang.c Subject: Re: Initializing arrays of char Message-ID: <26860@mimsy.umd.edu> Date: 5 Oct 90 14:21:41 GMT References: <1990Oct4.152756.6850@micrognosis.co.uk> <15674@csli.Stanford.EDU> Organization: U of Maryland, Dept. of Computer Science, Coll. Pk., MD 20742 Lines: 67 In article <15674@csli.Stanford.EDU> poser@csli.Stanford.EDU (Bill Poser) writes: >Regarding the assignment of "12345" to char x[5] ... [K&R 2 says] > ...the number of characters in the string, NOT COUNTING > THE TERMINATING NULL CHARACTER, must not exceed the > size of the array. [emphasis mine] >Can anyone explain [why the ending '\0' is not counted]? This is a change in New (ANSI) C. In Classic (K&R-1) C, a double-quoted string in an initializer context%, when setting the initial value of a character array, was treated uniformly as if it were a bracketed initializer consisting of all the characters, including the terminating NUL, in the string. That is, char x[5] = "12345"; meant exactly the same thing as char x[5] = { '1', '2', '3', '4', '5', '\0' }; (and was therefore in error, having too many characters). The X3J11 committee decided# that this was overly restrictive, and relaxed the rule to `is equivalent to a bracketed initializer consisting of all the characters, including the terminating NUL if it fits'. Thus char x[] = "12345"; means the same as char x[] = { '1', '2', '3', '4', '5', '\0' }; or char x[6] = { '1', '2', '3', '4', '5', '\0' }; but char x[5] = "12345"; now means the same as char x[5] = { '1', '2', '3', '4', '5' }; If the declaration is changed to char x[4] = "12345"; it is once again in error. ----- % Note that here (in an initializer context) and as an argument to sizeof (e.g., `sizeof "abc"') are the only two places that a double quoted string does not undergo the usual `array degenerates into pointer' rule. All other legal occurrences of a double-quoted string are in a value context, and therefore change from `array N of char' to `pointer to char', pointing to the first character in the string. # This wording is not meant to imply judgement as to this decision. (When I do not take a stand on some aspect of the language I use weasel-wording like `seems to be' or merely present bare facts.) Since I use old compilers, I have not made up my mind on this. I am leaning towards the `not a bad idea after all' faction. -- In-Real-Life: Chris Torek, Univ of MD Comp Sci Dept (+1 301 405 2750) Domain: chris@cs.umd.edu Path: uunet!mimsy!chris