2011-09-25 103 views
4

我:问题字符数组=字符数组

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

当我尝试做message1 = message2,我得到错误:

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

我有一个像

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

插图中的功能。莫名其妙地搞砸了吗? :(

我有一种感觉,也许你不能做=的字符数组或东西,但我环顾四周,找不到任何东西。

+0

你使用的是C++编译器吗? –

回答

1

你的怀疑是正确的,C(我假设这是C)把数组变量作为指针

你需要了解数组和指针的C FAQ:。http://c-faq.com/aryptr/index.html

+2

排序,但不是真的。 –

+1

更确切地说,数组类型的表达式(例如数组变量的名称)会在* most *上下文中隐式转换为指向数组对象第一个元素的指针。但引用我最喜欢的FAQ部分+1。 –

+0

这个FAQ比你更精确... –

10

can't assign anything to an array variable in C这不是一个“修改的左值”从属,§6.3。 .2.1左值,数组和函数标识符

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.

您收到的错误消息有点令人困惑,因为表达式右侧的数组在指定前衰减为指针。你有什么是语义上等效于:

message1 = &message2[0]; 

这给右侧类型char *,但因为你仍然不能分配什么message1(它是一个数组,类char[100]),你得到的编译器错误你看到的。您可以通过使用memcpy(3)解决您的问题:

memcpy(message1, message2, sizeof message2); 

如果真有你的心脏上使用=出于某种原因设置,你可以使用内部结构使用数组...这不是真的走了推荐的方式,虽然。