C++Talk.NET Forum Index C++Talk.NET
C++ language newsgroups
 
Archives   FAQFAQ   SearchSearch   MemberlistMemberlist   UsergroupsUsergroups   RegisterRegister 
 ProfileProfile   Log in to check your private messagesLog in to check your private messages   Log inLog in 

Re: initialize char-array with string

 
Post new topic   Reply to topic    C++Talk.NET Forum Index -> C Language (Moderated)
View previous topic :: View next topic  
Author Message
Francis Glassborow
Guest





PostPosted: Mon Jul 28, 2003 10:27 pm    Post subject: Re: initialize char-array with string Reply with quote



In article <clcm-20030728-0002 (AT) plethora (DOT) net>, Georg Klein
<kronion (AT) gmx (DOT) de> writes
Quote:
hi all,

this might be a beginner's problem, but I'm sure you can help me with this:

I want to declare a char-array and initialize it with a string.

this listing does work:

char v[20]="text";

That is initialisation of an array with another array, a valid operation
in C
Quote:

this doesn't:

char v[20];
v="text";

That is assignment of an array to another which is invalid in C. You
need to use strcpy:

strcpy(y, text);

Quote:

the compiler tells me there were "incompatible types in assignment" but why?

thx and so long

Georg Klein

--
Francis Glassborow ACCU
64 Southfield Rd
Oxford OX4 1PA +44(0)1865 246490
All opinions are mine and do not represent those of any organisation
--
comp.lang.c.moderated - moderation address: [email]clcm (AT) plethora (DOT) net[/email]

Back to top
Ajoy K Thamattoor
Guest





PostPosted: Sun Aug 03, 2003 3:49 am    Post subject: Re: initialize char-array with string Reply with quote



Herbert Rosenau wrote:
Quote:
this might be a beginner's problem, but I'm sure you can help me with this:

I want to declare a char-array and initialize it with a string.

this listing does work:

char v[20]="text";

A string has type array of char. Which is why this intialization
works.
That is easy enough to understand.

Quote:
this doesn't:

char v[20];

declaration or definition without initialisation.


v="text";

This one is harder. In a nutshell, it is wrong because that is
the way it is.
The standard has a lot of gobbledygook on array types decaying
into ptr-to-array-elem types (which are r-values, and not l-values), and
exceptions to the decay rule for string-initializers and the sizeof
operator.

That is just a way to precisely formalize the following rules:

char a[20] = "abcd"; is OK

char a[20], *b;
a = "abcd"; is not OK.
b = "abcd"; is OK.

char a[20], *b;
b = a; is Ok.
a = b; is not Ok.

char a[sizeof "abcd"] = "abcd"; is Ok.

char *b = "abcd";
char a [sizeof b] = "abcd"; is not Ok.

Ajoy.
--
comp.lang.c.moderated - moderation address: [email]clcm (AT) plethora (DOT) net[/email]

Back to top
Post new topic   Reply to topic    C++Talk.NET Forum Index -> C Language (Moderated) All times are GMT
Page 1 of 1

 
 


Powered by phpBB © 2001, 2006 phpBB Group