简体   繁体   中英

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.

#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"};

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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