C Board  

Go Back   C Board > General Programming Boards > C Programming

Reply
 
LinkBack Thread Tools Display Modes
Old 11-07-2009, 11:25 AM   #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.
bwisdom is offline   Reply With Quote
Old 11-07-2009, 11:33 AM   #2
Jack of many languages
 
Join Date: Nov 2007
Location: Katy, Texas
Posts: 1,929
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)
__________________
Mac and Windows cross platform programmer. Ruby lover.

Memorable Quotes From Recent Posts:

I can't remember.

Last edited by Dino; 11-07-2009 at 11:36 AM.
Dino is offline   Reply With Quote
Old 11-07-2009, 11:34 AM   #3
The larch
 
Join Date: May 2006
Posts: 3,082
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.

Quote:
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).
anon is offline   Reply With Quote
Reply

Thread Tools
Display Modes

Forum Jump

Similar Threads
Thread Thread Starter Forum Replies Last Post
Game of life: Initializing a struct with two 2D arrays Brafil C Programming 23 12-06-2008 01:39 PM
newbee: initializing arrays breaka C Programming 11 06-12-2006 12:20 PM
Initializing dynamic arrays cunnus88 C++ Programming 9 11-21-2005 09:50 AM
initializing values for arrays, and chaging them w/o using scanf sly_ C Programming 14 03-17-2003 10:07 AM
initializing char arrays to null swiss powder C++ Programming 6 02-28-2002 02:56 PM


All times are GMT -6. The time now is 09:14 AM.


Powered by vBulletin® Version 3.8.1
Copyright ©2000 - 2009, Jelsoft Enterprises Ltd.
Search Engine Optimization by vBSEO 3.3.0 RC2

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