Initializing arrays

This is a discussion on Initializing arrays within the C Programming forums, part of the General Programming Boards category; I have a question. If: Code: char s[]="abc"; works, why doesn't Code: char s[8]; s[]="abc"; work. My line of thinking ...

  1. #1
    Registered User
    Join Date
    Feb 2008
    Posts
    12

    Initializing arrays

    I have a question. If:

    Code:
    char s[]="abc";
    works, why doesn't

    Code:
    char s[8];
    s[]="abc";
    work. My line of thinking is that they both initilize an array of a certain size and then put the string "abc" in it. What am I missing? Ill get a "parse error before ']' token" in the second code on line 2.

    The reason I would want the second alternative is lets say I have conditions with which I want to apply to s[]. Depending on the condition it will house a different string(none of which are longer than the array, including \0 of course), I would then want to print s[]. How would I get something like that to work?
    Last edited by bwisdom; 11-07-2009 at 11:35 AM.

  2. #2
    Jack of many languages Dino's Avatar
    Join Date
    Nov 2007
    Location
    Katy, Texas
    Posts
    2,309
    You have to use strcpy() in C (or an equivalent function). In C, you can't just assign a string to a string variable. (edit: unless you are declaring it, and then that action happens at compile time, not runtime)
    Last edited by Dino; 11-07-2009 at 11:36 AM.
    Mac and Windows cross platform programmer. Ruby lover.

    Quote of the Day
    12/20: Mario F.:I never was, am not, and never will be, one to shut up in the face of something I think is fundamentally wrong.

    Amen brother!

  3. #3
    The larch
    Join Date
    May 2006
    Posts
    3,573
    Because initializing only works where you declare things. Arrays cannot be assigned later.

    So look into strcpy, to set the string contents later.
    I might be wrong.

    Thank you, anon. You sure know how to recognize different types of trees from quite a long way away.
    Quoted more than 1000 times (I hope).

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Replies: 23
    Last Post: 12-06-2008, 01:39 PM
  2. newbee: initializing arrays
    By breaka in forum C Programming
    Replies: 11
    Last Post: 06-12-2006, 01:20 PM
  3. Initializing dynamic arrays
    By cunnus88 in forum C++ Programming
    Replies: 9
    Last Post: 11-21-2005, 09:50 AM
  4. Replies: 14
    Last Post: 03-17-2003, 10:07 AM
  5. initializing char arrays to null
    By swiss powder in forum C++ Programming
    Replies: 6
    Last Post: 02-28-2002, 02:56 PM

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21