“错误:分配给具有数组类型错误的表达式"当我分配一个结构字段(C) [英] "error: assignment to expression with array type error" when I assign a struct field (C)
问题描述
我是C语言的初学者,昨天我了解了C结构的使用以及这些结构在解决特定问题方面的可能应用.但是,当我尝试使用C IDE(代码块16.01)来学习C编程的这一方面时,遇到了一个奇怪的问题.代码如下:
I'm a beginner C programmer, yesterday I learned the use of C structs and the possible application of these ones about the resolution of specific problems. However when I was experimenting with my C IDE (Codeblocks 16.01) in order to learn this aspect of C programming, I've encountered a strange issue. The code is the following:
#include <stdio.h>
#define N 30
typedef struct{
char name[N];
char surname[N];
int age;
} data;
int main() {
data s1;
s1.name="Paolo";
s1.surname = "Rossi";
s1.age = 19;
getchar();
return 0;
}
在编译期间,编译器(Windows下为GCC 4.9.3-1)向我报告了一条错误消息
During the compilation, the compiler (GCC 4.9.3-1 under Windows) reported me an error that says
错误:分配给具有数组类型错误的表达式"
"error: assignment to expression with array type error"
根据说明
s1.name="Paolo"
s1.surname="Rossi"
如果我愿意的话
data s1 = {"Paolo", "Rossi", 19};
有效. 我究竟做错了什么?
it works. What am I doing wrong?
推荐答案
您面临的问题
s1.name="Paolo";
因为在LHS中,您使用的是 array 类型,该类型不是可分配的.
because, in the LHS, you're using an array type, which is not assignable.
要详细说明,请参见C11
第6.5.16章
To elaborate, from C11
, chapter §6.5.16
赋值运算符的左值应为可修改的左值.
assignment operator shall have a modifiable lvalue as its left operand.
,关于可修改的左值,请参见第6.3.2.1章
and, regarding the modifiable lvalue, from chapter §6.3.2.1
可修改的左值是一个 没有数组类型,[...]
A modifiable lvalue is an lvalue that does not have array type, [...]
您需要使用strcpy()
来复制到阵列中.
也就是说,data s1 = {"Paolo", "Rossi", 19};
可以正常工作,因为这不是直接涉及赋值运算符的赋值.在这里,我们使用了一个括起来的初始化程序列表,以提供 object 的初始值.遵循第6.7.9章中所述的初始化定律
That said, data s1 = {"Paolo", "Rossi", 19};
works fine, because this is not a direct assignment involving assignment operator. There we're using a brace-enclosed initializer list to provide the initial values of the object. That follows the law of initialization, as mentioned in chapter §6.7.9
每个用大括号括起来的初始化器列表都有一个关联的当前对象.当没有 存在指定,当前对象的子对象按以下顺序初始化 到当前对象的类型:下标顺序递增的数组元素,结构 成员按声明顺序排列,并且是联盟的第一个命名成员.[....]
Each brace-enclosed initializer list has an associated current object. When no designations are present, subobjects of the current object are initialized in order according to the type of the current object: array elements in increasing subscript order, structure members in declaration order, and the first named member of a union.[....]
这篇关于“错误:分配给具有数组类型错误的表达式"当我分配一个结构字段(C)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!