Initializing arrays of char

Dan Bernstein brnstnd at kramden.acf.nyu.edu
Fri Oct 5 13:06:27 AEST 1990


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 ]

More to the point, an alert reader will notice that you haven't
accounted for the NULL. Whether or not that's legal, you should always
treat non-string (i.e., non-NULL-terminated) character arrays as real
arrays with no relation between consecutive characters. Something like

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

This expresses your intent much more clearly.

> 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";.)

Am I reading your mind correctly? :-)

---Dan



More information about the Comp.lang.c mailing list