gpt4 book ai didi

c - 是否可以在不事先定义的情况下将结构变量作为函数参数传递?

转载 作者:太空狗 更新时间:2023-10-29 15:03:29 26 4
gpt4 key购买 nike

我定义了两个结构(在 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. 我能做我想做的事吗(但显然是以不同的方式)?

  2. 如果是 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/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com