2011-09-25 57 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); 

如果真有你的心臟上使用=出於某種原因設置,你可以使用內部結構使用數組...這不是真的走了推薦的方式,雖然。