Welcome to WuJiGu Developer Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
379 views
in Technique[技术] by (71.8m points)

c - problems with char array = char array

I have:

char message1[100];
char message2[100];

When I try to do message1 = message2, I get error:

incompatible types when assigning to type ‘char[100]’ from type ‘char *’

I have functions like

if(send(clntSocket, echoBuffer, recvMsgSize, 0) != recvMsgSize){
   DieWithError("send() failed")
}

inbetween. Could these mess things up somehow? :(

I have a feeling maybe you can't do = on char arrays or something, but I looked around and couldn't find anything.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

You can't assign anything to an array variable in C. It's not a 'modifiable lvalue'. From the spec, §6.3.2.1 Lvalues, arrays, and function designators:

An lvalue is an expression with an object type or an incomplete type other than void; if an lvalue does not designate an object when it is evaluated, the behavior is undefined. When an object is said to have a particular type, the type is specified by the lvalue used to designate the object. A modifiable lvalue is an lvalue that does not have array type, does not have an incomplete type, does not have a const-qualified type, and if it is a structure or union, does not have any member (including, recursively, any member or element of all contained aggregates or unions) with a const-qualified type.

The error message you're getting is a bit confusing because the array on the right hand side of the expression decays into a pointer before the assignment. What you have is semantically equivalent to:

message1 = &message2[0];

Which gives the right side type char *, but since you still can't assign anything to message1 (it's an array, type char[100]), you're getting the compiler error that you see. You can solve your problem by using memcpy(3):

memcpy(message1, message2, sizeof message2);

If you really have your heart set on using = for some reason, you could use use arrays inside structures... that's not really a recommended way to go, though.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to WuJiGu Developer Q&A Community for programmer and developer-Open, Learning and Share
...