c - "error: assignment to expression with array type error"当我分配一个结构字段 (C)

标签 c arrays string struct initialization

我是一名初级C程序员,昨天学习了C结构体的使用以及这些结构体在解决具体问题时的可能应用。然而,当我为了学习 C 编程的这一方面而试验我的 C IDE (Codeblocks 16.01) 时,我遇到了一个奇怪的问题。代码如下:

#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)向我报告了一个错误

"error: assignment to expression with array type error"

根据指示

s1.name="Paolo" 
s1.surname="Rossi" 

如果我这样做

data s1 = {"Paolo", "Rossi", 19};

它有效。 我究竟做错了什么?

最佳答案

您遇到的问题是

 s1.name="Paolo";

因为在 LHS 中,您使用的是 数组 类型,该类型不可分配

详细说明,来自 C11,章节 §6.5.16

assignment operator shall have a modifiable lvalue as its left operand.

并且,关于可修改的左值,来自章节 §6.3.2.1

A modifiable lvalue is an lvalue that does not have array type, [...]

您需要使用 strcpy()复制到数组中。

也就是说,data s1 = {"Paolo", "Rossi", 19}; 工作正常,因为这不是涉及赋值运算符的直接赋值。我们使用一个大括号括起来的初始化列表来提供对象的初始值。这遵循初始化法则,如第 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 - "error: assignment to expression with array type error"当我分配一个结构字段 (C),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37225244/

相关文章:

在以下代码中找不到一个字节的内存泄漏

c - 在有操作系统和无操作系统的嵌入式设备上编程的区别

c - 为什么我总是覆盖链接列表中指向的内容?

php - 数组上的奇怪打印

python - 替换 python 中的精确子字符串

string - 在 Smalltalk VisualWorks 7.9.1 中将 Open Sound Control ByteArray 转换为 String

c++ - 在 CMake 中调试与发布

c++ - 使用索引重置数组

java - 直接从字节数组播放声音 - Java

R将大字符串转换为数据帧