0

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!

1 Answer 1

3

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"};
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.