为什么 C 允许使用“var = (struct NAME){…}”为结构体变量赋值?

问题描述 投票:0回答:1

在我认为我无法将整个值赋给结构变量之前。

这其实是错误的:

struct Student student1;
student1 = {"Andy", 18};

但我想我只能用:

struct Student student1;
student1.name = "Andy";
student1.age=18;

今天,我发现我可以使用下面的格式来做到这一点,带有前缀“(struct Student)”,但是我很难理解:

struct Student student1;
student1 = (struct Student){"Andy", 18}; // it is ok
c struct
1个回答
0
投票

在第三个示例中,您正在创建一个未命名的对象。这在您的第一个示例中不起作用,因为对象的类型(以及大小)未知。

注意,你可以完美地写:

struct Student student1;
struct Student student2;

student1.name = "abc";
student1.age = 3;

student2 = student1;
© www.soinside.com 2019 - 2024. All rights reserved.