gpt4 book ai didi

arrays - 您可以为 C 中的二维数组的 struct 中的所有元素赋值吗?

转载 作者:行者123 更新时间:2023-12-02 18:03:52 24 4
gpt4 key购买 nike

我想制作一个灰度滤镜,因此我必须将所有 3 个 RGB 值的平均值分配给每个滤镜。我使用 2D 数组,因为这是一个位图图像,我通过更改每个像素来过滤它。

这就是结构体的定义方式(其中 BYTEuint8_t):

typedef struct
{
BYTE rgbtBlue;
BYTE rgbtGreen;
BYTE rgbtRed;
} __attribute__((__packed__))
RGBTRIPLE;

我是否需要像下面那样分别为结构的每个元素分配值,或者有没有办法将该值分配给结构中特定位置的所有元素(因为它们是相同的类型)一次数组?

这是过滤功能的代码。

void grayscale(int height, int width, RGBTRIPLE image[height][width])
{
for (int i = 0; i < height; i++)
{
for (int j = 0 ; j < width; j++)
{
image[i][j].rgbtBlue = (image[i][j].rgbtBlue + image[i][j].rgbtRed + image[i][j].rgbtGreen)/3;
image[i][j].rgbtGreen = (image[i][j].rgbtBlue + image[i][j].rgbtRed + image[i][j].rgbtGreen)/3;
image[i][j].rgbtRed = (image[i][j].rgbtBlue + image[i][j].rgbtRed + image[i][j].rgbtGreen)/3;
}
}
return;
}

最佳答案

您可以使用复合文字来做到这一点:

RGBTRIPLE x = image[i][j];  // Use temporary to reduce repetition.
BYTE t = (x.rgbtBlue + x.rgbtRed + x.rgbtGreen)/3;
image[i][j] = (RGBTRIPLE) { t, t, t };

关于arrays - 您可以为 C 中的二维数组的 struct 中的所有元素赋值吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/73735230/

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