当前位置: 华文星空 > 知识

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