Initializing arrays of char

Chris Edgington *Computer Science Major* edgincd2 at mentor.cc.purdue.edu
Fri Oct 5 11:14:08 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 ?
> 
> struct foo {
> 	char x[5];
> 	} bar = {"12345"};
> 
> char baz[5] = "12345";
> 
When you request the compiler to allocate n chars in the array, you really
should only use the first 4 if you are going to be using the array as a 
string because one of the chars allocated is used for the NULL, which tells
the compiler where the end of the string is.  If you write over the NULL and 
then try to print the string, the compiler [runtime code] will just continue
printing until it encounters a NULL, signifying the end of the string.  
Therefore, to allocate ample space for your string "12345", you need to have
char baz[6].


   __                     __
  /  ) /                 /  `    /                _/_
 /    /_  __  o _       /--   __/ _,  o ____  _,  /  ________
(__/ / /_/ (_<_/_)_    (___, (_/_(_)_<_/ / <_(_)_<__(_) / / <_
                                  /|          /|
                                 |/          |/
Chris Edgington      edgincd2 at mentor.cc.purdue.edu       Purdue University



More information about the Comp.lang.c mailing list