简体   繁体   中英

How can I pass a struct compound literal to a function as argument?

Here is a struct that I have:

typedef struct 
{
    float r, g, b;
} color_t;

I'd like to pass a compound literal of this struct to a function as argument, like this:

void printcolor(color_t c)
{
    printf("color is : %f %f %f\n", c.r, c.g, c.b);
}

printcolor({1.0f, 0.6f, 0.8f});

However, this gives me an error:

error: expected expression before '{' token

A compound literal in C must have the type specified (using 'cast-like' syntax) before the brace-enclosed initializer list. So, as mentioned in the comments, you should change your function call to:

printcolor((color_t){1.0f, 0.6f, 0.8f});

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