【问题标题】:How do i pass an array of structs by reference to a function?如何通过引用函数来传递结构数组?
【发布时间】:2020-12-07 00:17:49
【问题描述】:

我需要编写一个函数,通过将图像中的像素包含在二维结构数组中来反映图像。下面是我编写的函数,它基本上用第一个像素切换最后一个像素,依此类推,但我需要它来编辑原始数组,而不是当前未执行的副本。下面是 main 中的函数以及函数的布局方式。任何输入都会有所帮助!

reflect(height, width, &image);

功能:

void reflect(int height, int width, RGBTRIPLE *image[height][width])
{
    RGBTRIPLE temp;
    for ( int i = 0 ; i < height ; i++)
    {
        for( int j = 0 ; j < width ; j++)
        {
            temp = image[i][j];
            image[i][j] = image[i][width-j-1];
            image[i][width-1-j]=temp;

        }
    }
}

结构如下图

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

结构数组是使用这个创建的:

    // Allocate memory for image
    RGBTRIPLE(*image)[width] = calloc(height, width * sizeof(RGBTRIPLE));

【问题讨论】:

  • 不要使用二维结构,使用一维结构。使用它要容易得多。在这种情况下,编译器不能使用一个参数来指示另一个参数的类型。
  • @tadman 我目前正在上 CS50 课程,这就是他们要求我们做的。我已经在 1D 结构中尝试过它并且它可以工作,但我需要使用这种方法使其工作。
  • 经过进一步思考,为什么不将其视为原始字节数组并使用偏移计算和一些memcpy 正确导航它?
  • j &lt; width/2 或者你反映两次
  • @tadman 刚刚编辑了帖子

标签: arrays c struct pass-by-reference swap


【解决方案1】:

对于初学者来说,函数应该被声明为

void reflect(int height, int width, RGBTRIPLE image[height][width]);

或喜欢

void reflect(int height, int width, RGBTRIPLE image[][width]);

或喜欢

void reflect(int height, int width, RGBTRIPLE ( *image )[width]);

并像这样称呼

reflect(height, width, image);

在函数内循环应该是这样的

for ( int i = 0 ; i < height ; i++)
{
    for( int j = 0 ; j < width / 2 ; j++)
    {
        temp = image[i][j];
        image[i][j] = image[i][width-j-1];
        image[i][width-1-j]=temp;

    }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-10-30
    • 2018-01-18
    • 1970-01-01
    • 2011-05-06
    • 1970-01-01
    相关资源
    最近更新 更多