首页 > 解决方案 > 如何将结构复合文字作为参数传递给函数?

问题描述

这是struct我所拥有的:

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

我想将 this 的复合文字struct作为参数传递给函数,如下所示:

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});

但是,这给了我一个错误:

错误:“{”标记之前的预期表达式

标签: ccompound-literals

解决方案


C 中的复合文字必须在大括号括起来的初始值设定项列表之前具有指定的类型(使用'cast-like'语法)。因此,如评论中所述,您应该将函数调用更改为:

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

推荐阅读