當前位置: 華文星空 > 知識

C語言為什麽結構體能用等號賦值,字元陣列卻不行?

2021-06-16知識

因為對於等號來說,它們不是字元陣列。

int a = 10 ; int b ; b = a ; // 這裏的運算式 b 和 a 都是 int 類別 struct Student s1 = { 18 , "mike" , 59 }; struct Student s2 ; s2 = s1 ; // 這裏的運算式 s2 和 s1 都是 struct Student 類別 char foo [] = "foo" ; char bar [ sizeof ( foo )]; bar = foo ; // 這裏的運算式 bar 和 foo 都是 char * 類別(指標)的非左值,不是陣列

只要不是 sizeof 、單目 & 等等少數操作符的運算元,陣列類別的運算式都會首先被轉換為對應的指標類別的非左值。

Except when it is the operand of the sizeof operator, the _Alignof operator, or the unary & operator, or is a string literal used to initialize an array, an expression that has type ''array of type'' is converted to an expression with type ''pointer to type'' that points to the initial element of the array object and is not an lvalue. [1]

然後既然是非左值,你就沒法往裏面賦值了,甚至不用考慮類別。

至於為啥要搞這種轉換,是為了相容 B 語言程式碼,見 c++不提供陣列賦值語法的理由是什麽?

參考

  1. ^ C11 6.3.2.1 Lvalues, arrays, and function designators https://port70.net/~nsz/c/c11/n1570.html#6.3.2.1p3