Re: Character array initialization

From: Richard Tobin (richard_at_cogsci.ed.ac.uk)
Date: 08/04/04


Date: 4 Aug 2004 15:29:29 GMT

In article <2ncd60Fuh2hiU1@uni-berlin.de>,
Christian Kandeler <christian.kandeler@hob.de> wrote:

>That's why it is a mistake to write this:
>
>char s[6] = "123456";

It's *often* a mistake.

But try this:

char s[5] = "123456";

I expect your compilers will generate a diagnostic.

What's the difference? There's no requirement in C that arrays of
characters be null-terminated. There are just a bunch of functions
that expect it. It's quite reasonable to initialize an array of 6
characters with 6 non-null characters. On the other hand, it makes no
sense to initialize an array of 5 characters with 6 characters.

-- Richard



Relevant Pages

  • Re: Array reinitialize
    ... |> | by a character string literal, ... |> | initialize the elements of the array." ... | is really 21 characters long. ... an array via an aggregate initialiser, ...
    (alt.comp.lang.learn.c-cpp)
  • Re: sending echo to all clients
    ... I did initialize it up properly, ... There is only one array and that is an array of pollfd structures named ... as an array of characters only but then I can't because sendsends bytes ... So you are sending the clients the wrong number of bytes. ...
    (comp.unix.programmer)
  • Re: sending echo to all clients
    ... I did initialize it up properly, ... There is only one array and that is an array of pollfd structures named ... as an array of characters only but then I can't because sendsends bytes ... you receive C-style strings, so there's really no point to doing it. ...
    (comp.unix.programmer)
  • Re: TCHAR, terminating and _tcscat
    ... That doesn't guarantee newstring "will always be nul-terminated". ... Note also that I don't need to initialize ... and if it copies fewer characters than the ... does it makes sense to fill an array with 250 zeroes and then ...
    (microsoft.public.vc.mfc)
  • Re: test if handle exists? How???
    ... > ishandlegives an array of nine 0s ... does not work because 'handles.c' is a literal character vector of 9 characters and that character vector is not an empty array. ... If what you are trying to do is find out whether there is a graphics object with the tag 'abcdef' then use ...
    (comp.soft-sys.matlab)