我定义了两个结构(在 color.h
中):
typedef struct rgb {
uint8_t r, g, b;
} rgb;
typedef struct hsv {
float h, s, v;
} hsv;
hsv rgb2hsv(rgb color);
rgb hsv2rgb(hsv color);
然后我在 main.c
中有以下有效:
hsv hsvCol = {i/255.0, 1, 1};
rgb col = hsv2rgb(hsvCol);
我希望能够在 hsv2rgb
的参数中创建变量 hsvCol
,而不必创建变量并将其作为参数传递。
我已经尝试了以下每一个(代替上面的两行),遗憾的是没有一个编译:(
rgb col = hsv2rgb({i/255.0, 1, 1});
rgb col = hsv2rgb(hsv {i/255.0, 1, 1});
rgb col = hsv2rgb(hsv hsvCol {i/255.0, 1, 1})
rgb col = hsv2rgb(struct hsv {i/255.0, 1, 1});
我的问题是:
我能做我想做的事吗(但显然是以不同的方式)?
如果是 1,我该怎么做?
最佳答案
您可以使用 compound literal .
引用 C11
,章节 §6.5.2.5,第 3 段,
A postfix expression that consists of a parenthesized type name followed by a brace enclosed list of initializers is a compound literal. It provides an unnamed object whose value is given by the initializer list.
和第 5 段,
The value of the compound literal is that of an unnamed object initialized by the initializer list. [...]
因此,在您的情况下,代码如下
hsv hsvCol = {i/255.0, 1, 1};
rgb col = hsv2rgb(hsvCol);
可以重写为
rgb col = hsv2rgb( ( hsv ) {i/255.0, 1, 1} );
^^^^ ^^^^^^^^^^^^^
| |
| -- brace enclosed list of initializers
-- parenthesized type name
关于c - 是否可以在不事先定义的情况下将结构变量作为函数参数传递?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42350203/