char array Q

Discussion in 'C Programming' started by suresh shenoy, Feb 20, 2008.

  1. I know that
    char s[100];
    s = "xyz";
    is invalid and should use char ptr or string library to store a string
    literal in s. Can anyone be precise why the second line is invalid?
     
    suresh shenoy, Feb 20, 2008
    #1
    1. Advertising

  2. suresh shenoy said:

    > I know that
    > char s[100];
    > s = "xyz";
    > is invalid and should use char ptr or string library to store a string
    > literal in s. Can anyone be precise why the second line is invalid?


    The assignment operator requires as its left operand a modifiable lvalue.
    Arrays are not modifiable lvalues.

    Initialisation with a string literal is, however, permissible:

    char s[100] = "xyz";

    The contents of s are now 'x', 'y', 'z', and 97 '\0's.

    --
    Richard Heathfield <http://www.cpax.org.uk>
    Email: -http://www. +rjh@
    Google users: <http://www.cpax.org.uk/prg/writings/googly.php>
    "Usenet is a strange place" - dmr 29 July 1999
     
    Richard Heathfield, Feb 20, 2008
    #2
    1. Advertising

  3. suresh shenoy

    Guest

    On Feb 20, 1:42 pm, Richard Heathfield <> wrote:
    > suresh shenoy said:
    >
    > > I know that
    > > char s[100];
    > > s = "xyz";
    > > is invalid and should use char ptr or string library to store a string
    > > literal in s. Can anyone be precise why the second line is invalid?

    > char s[100] = "xyz";
    >
    > The contents of s are now 'x', 'y', 'z', and 97 '\0's.


    Just wanted to mention why this happends;
    In array initialization, when the initialization does not initialize
    all the elements of the array, the rest are given the value 0 (or NULL
    in pointer context)
    Notice, I said the rest; which means int foo[3] = { [1] = 42 };
    guarantees foo[0] to be 0.
     
    , Feb 20, 2008
    #3
    1. Advertising

Want to reply to this thread or ask your own question?

It takes just 2 minutes to sign up (and it's free!). Just click the sign up button to choose a username and then you can ask your own questions on the forum.
Similar Threads
  1. wwj
    Replies:
    7
    Views:
    581
  2. lovecreatesbeauty
    Replies:
    1
    Views:
    1,099
    Ian Collins
    May 9, 2006
  3. Replies:
    3
    Views:
    745
  4. davidb
    Replies:
    0
    Views:
    774
    davidb
    Sep 1, 2006
  5. davidb
    Replies:
    6
    Views:
    1,566
    Default User
    Sep 1, 2006
Loading...

Share This Page