简体   繁体   English

为结构数组赋值

[英]Assigning values to a struct array

I am trying to assign values to a struct array.我正在尝试为结构数组赋值。 However, I'm getting the "Expected expression" error.但是,我收到“预期表达式”错误。 Is there something that I'm missing?有什么我想念的吗? I'm using Xcode in case that matters.我正在使用 Xcode 以防万一。

#include <stdio.h>
#include <stdlib.h>

struct MEASUREMENT
{
    float relativeHumidity;
    float temperature;
    char timestamp[20];
};

int main()
{
    struct MEASUREMENT measurements[5];
    
    measurements[0] = {0.85, 23.5, "23.07.2019 08:00"}; //Expected expression error
    measurements[1] = {0.71, 19.0, "04.08.2019 10:21"}; //Expected expression error
    measurements[2] = {0.43, 10.2, "07.08.2019 02.00"}; //Expected expression error
    measurements[3] = {0.51, 14.3, "20.08.2019 14:45"}; //Expected expression error
    measurements[4] = {0.62, 10.9, "01.09.2019 01:00"}; //Expected expression error

Thanks!谢谢!

Listing values in braces is a special syntax for initializations in declarations.在大括号中列出值是声明中初始化的特殊语法。 A list in braces does not by itself form an expression that can be used in assignments.花括号中的列表本身并不构成可用于赋值的表达式。

You can provide initial values in this form when defining the array:您可以在定义数组时以这种形式提供初始值:

struct MEASUREMENT measurements[5] = {
        {0.85, 23.5, "23.07.2019 08:00"},
        {0.71, 19.0, "04.08.2019 10:21"},
        {0.43, 10.2, "07.08.2019 02.00"},
        {0.51, 14.3, "20.08.2019 14:45"},
        {0.62, 10.9, "01.09.2019 01:00"},
    };

In expressions, you can define a temporary object using a compound literal and then assign its value to another object.在表达式中,您可以使用复合字面量定义一个临时对象,然后将其值分配给另一个对象。 A compound literal is formed with a type in parentheses followed by a brace-enclosed list of initializers:复合文字由括号中的类型后跟花括号括起来的初始值设定项列表构成:

measurements[0] = (struct MEASUREMENT) {0.85, 23.5, "23.07.2019 08:00"};
measurements[1] = (struct MEASUREMENT) {0.71, 19.0, "04.08.2019 10:21"};
measurements[2] = (struct MEASUREMENT) {0.43, 10.2, "07.08.2019 02.00"};
measurements[3] = (struct MEASUREMENT) {0.51, 14.3, "20.08.2019 14:45"};
measurements[4] = (struct MEASUREMENT) {0.62, 10.9, "01.09.2019 01:00"};

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM