我正在尝试我的手在CS50的过滤器,我在像素部分的模糊。我可以使用
来访问像素的颜色image[row][pixel].rgbtRed
image[row][pixel].rgbtGreen
image[row][pixel].rgbtBlue
我希望能够调用一个函数来计算周围像素的平均值,并传入我想要的平均值的颜色。是否有某种占位符,以便我可以访问结构体的特定元素/属性?(对不起,我不确定它的正确名称)。
我还是一个新手,试着把它放在括号之间,但是没有效果。
这里是我试图获得传递的颜色的值的函数。
float calcAverage(int height, int width, RGBTRIPLE image[height][width], int row, int pixel, string color)
{
float sum = image[row][pixel].color + image[row][pixel - 1].color;
return 0;
}
函数是这样调用的
redAverage = calcAverage(height, width, image, row, pixel, "rgbtRed");
现在我的。color计划不起作用,因为我知道他正在寻找一个名为color的属性。这是我得到的错误
error: no member named 'color' in 'RGBTRIPLE'
float sum = image[row][pixel].color + image[row][pixel - 1].color;
为了测试的目的,我把总和保持得很短。先谢谢你,我开始觉得这是不可能的,我应该离开它。如果我用了错误的术语来描述我要找的东西,再次表示抱歉。
这可以通过对成员进行偏移来实现,如下面的代码所示。从某种意义上说,使用这种方法有些笨拙。然而,在某些情况下,它可能是有用和适当的。由于使用了显式转换,覆盖了关于类型的常见编译器警告,因此必须非常小心。
typedef struct { float red, green, blue; } RGBTRIPLE;
#include <stdio.h>
#include <stddef.h>
/* Get the offset of a member in an RGBTRIPLE using the C standard "offsetof"
feature. This could be a function, preferably a static inline function
visible where it is used.
*/
#define OffsetOf(member) (offsetof(RGBTRIPLE, member))
/* Get a member of an RGBTRIPLE by its offset.
This uses the offset to locate the member and then converts the address to
a pointer to the member type, which we then use with "*" to refer to the
member. That produces an lvalue for the member which can be used to read
(use the value of) or write (assign to) the member.
This must be a macro because a function cannot return an lvalue.
*/
#define MemberByOffset(Structure, Offset)
(*(float *)((char *) &Structure + Offset))
static float Average(RGBTRIPLE *Array, size_t Offset)
{
static const size_t N = 2; // For demonstration only.
float sum = 0;
for (size_t i = 0; i < N; ++i)
sum += MemberByOffset(Array[i], Offset);
return sum/N;
}
int main(void)
{
RGBTRIPLE Array[] = {{ 10, 20, 30 }, { 100, 200, 300 }};
printf("Red average = %g.n", Average(Array, OffsetOf(red )));
printf("Green average = %g.n", Average(Array, OffsetOf(green)));
printf("Blue average = %g.n", Average(Array, OffsetOf(blue )));
}
不能使用字符串变量代替成员名。您需要检查字符串的值,并根据该值选择字段。
float calcAverage(int height, int width, RGBTRIPLE image[height][width],
int row, int pixel, string color)
{
if (!strcmp(color, "rgbtRed")) {
return image[row][pixel].rgbtRed + image[row][pixel - 1].rgbtRed;
} else if (!strcmp(color, "rgbtGreen")) {
return image[row][pixel].rgbtGreen + image[row][pixel - 1].rgbtGreen;
} else if (!strcmp(color, "rgbtBlue")) {
return image[row][pixel].rgbtBlue + image[row][pixel - 1].rgbtBlue;
} else {
// invalid color
return 0;
}
}