gpt4 book ai didi

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

转载 作者:太空狗 更新时间:2023-10-29 16:22:58 25 4
gpt4 key购买 nike

我是一名初级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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com