Initializing arrays of char

Jim Jagielski jim at jagmac2.gsfc.nasa.gov
Sat Oct 6 02:45:13 AEST 1990


In article <9418:Oct503:06:2790 at kramden.acf.nyu.edu> brnstnd at kramden.acf.nyu.edu (Dan Bernstein) writes:
>In article <14796 at mentor.cc.purdue.edu> edgincd2 at mentor.cc.purdue.edu (Chris Edgington *Computer Science Major*) writes:
>> In article <1990Oct4.152756.6850 at micrognosis.co.uk>, nreadwin at micrognosis.co.uk (Neil Readwin) writes:
>> > char baz[5] = "12345";
>  [ explanation ]
>
>> Therefore, to allocate ample space for your string "12345", you need to have
>> char baz[6].
>
>Only if you really do mean it that way---but from your article you
>obviously know how many characters to allocate for a NULL-terminated
>string, so you wouldn't be asking if that were the answer. (For those
>new to C, the easy way to allocate a string is char baz[] = "12345";.)
>                                               --------------------
                                                   ^
Let's clarify the above ---------------------------|


You forget that doing "char baz[] = "12345";" is the same as:

	char baz[] = { '1','2','3','4','5','\0' };

It appears in the above that you imply that doing char baz[] = "12345";
would result in a non-NULL-terminated string -- this is not correct.

Of course, I may not be reading your mind right :)

In any case, recall that C will always append the '\0' to any string constant.
If you don't want \0 in there, either copy upto the NULL (strncpy) or 
use characters ('a', etc...)
--
=======================================================================
#include <std/disclaimer.h>
                                 =:^)
           Jim Jagielski                    NASA/GSFC, Code 711.1
     jim at jagmac2.gsfc.nasa.gov               Greenbelt, MD 20771

"Kilimanjaro is a pretty tricky climb. Most of it's up, until you reach
 the very, very top, and then it tends to slope away rather sharply."



More information about the Comp.lang.c mailing list