c - 如何在 C 中为 Struct 属性赋值

标签 c struct properties

C 新手,这是我创建的一个简单结构。

typedef struct car {
    float x, y;             
    unsigned char width, height;    
} Cars;

我尝试分配汽车的 x 和 y 属性:

Cars sedan;
sedan.x = 20;
sedan.y = 10;

错误

error: expected '=', ',', ';', 'asm' or 'attribute' before '.' token

有什么想法吗?请帮忙!

最佳答案

我猜你有台词

Cars sedan;
sedan.x = 20;
sedan.y = 10;

在函数之外。你不能使用

sedan.x = 20;
sedan.y = 10;

在函数之外。将这些行移动到一个函数中。

另一种选择是使用(感谢@JonathanLeffler)初始化结构的成员

Car sedan = { .x = 20, .y = 10 };

关于c - 如何在 C 中为 Struct 属性赋值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40066862/

相关文章:

c - 在纯 C 中实现 RAII?

c - 采用并行处理的 OpenMP 基本温度建模比串行代码花费的时间更长

c++ - typedef struct 与 struct - ‘struct' 的存储大小未知

c - C中的字符串

c++ - C中数据的功能责任

c++ - 如何编写一个函数来测试链接列表是否已排序

无法打印结构

jsf - 如何从 JSF 的/WEB-INF 文件夹中获取属性文件?

C# 字段和属性

swift - 通过引用传递的自定义 swift 类属性?