在 C 中试验指针

Experimenting with Pointers in C

我是编码新手,大约一个月前开始了我的编码之旅。我刚刚完成了 CS50 的第 4 题,但想尝试一下指针。关于学术诚信 - 我已经提交了这个问题,这只是它的一个不同版本。

这是一个反射滤镜,用于镜像图像 RGBTRIPLE 包含图像中每个像素的红色、绿色和蓝色。 对于每一行,这应该交换水平相对侧的像素。对照片中的每一行重复此操作。

我想弄清楚是否可以使用指针来解决问题,但它似乎不起作用。这样不会只是将第一个像素的地址与最后一个像素的地址交换吗?甚至可以这样解决吗?同样,已经提交了这个特定的集合,只是想更好地理解指针的作用,以及是否有办法在它们的帮助下做到这一点。感谢您的帮助!

// Reflect image horizontally
   void reflect(int height, int width, RGBTRIPLE image[height][width])

for (int i = 0; i < height; i++)

    for (int j = 0; j < width / 2; j++)

        // find color values for first pixel
        int first_red = image [i][j].rgbtRed;
        int* pfirst_red = &first_red;

        int first_green = image [i][j].rgbtGreen;
        int* pfirst_green = &first_green;

        int first_blue = image [i][j].rgbtBlue;
        int* pfirst_blue = &first_blue;

        // find color values for last pixel
        int last_red = image[i][width - j - 1].rgbtRed;
        int* plast_red = &last_red;

        int last_green = image[i][width - j - 1].rgbtGreen;
        int* plast_green = &last_green;

        int last_blue = image[i][width - j - 1].rgbtBlue;
        int* plast_blue = &last_blue;
        
        // Convert first pixel to last
        pfirst_red = &last_red;
        pfirst_green = &last_green;
        pfirst_blue = &last_blue;

        // Convert last pixel to first
        plast_red = &first_red;
        plast_green = &first_green;
        plast_blue = &first_blue;


        
        :( reflect correctly filters 1x2 image
           expected "0 0 255\n255 0...", not "255 0 0\n0 0 2..."
        :( reflect correctly filters 1x3 image
           expected "0 0 255\n0 255...", not "255 0 0\n0 255..."
        :) reflect correctly filters image that is its own mirror image
        :( reflect correctly filters 3x3 image
           expected "70 80 90\n40 5...", not "10 20 30\n40 5..."
        :( reflect correctly filters 4x4 image
           expected "100 110 120\n7...", not "10 20 30\n40 5..."

首先我要检查 RGBTRIPLE 的声明,因为它的成员可能有一个不是 int 的大小。当使用大小不正确的指针时,相邻变量将被覆盖并破坏代码。

我在 google 上找到了这个,但请检查您的环境。

typedef struct
{
    BYTE  rgbtBlue;
    BYTE  rgbtGreen;
    BYTE  rgbtRed;
}
RGBTRIPLE;

在您的代码中,除了有一个指向大小不正确的项目的指针外,您还声明了一个局部变量,然后指向的是地址。

int last_red = image[i][width - j - 1].rgbtRed;
int* plast_red = &last_red;   // plast_red is a pointer to last_red

这只会让您交换局部变量的值。

您应该改为从结构中的数据中获取地址:

RGBTRIPPLE* ptriplet= last_red = image[i][width - j - 1];  // This is an alternative pointer to the struct
BYTE* plast_red = &image[i][width - j - 1].rgbtRed;

然后使用指针和交换的临时变量:

BYTE temp = *plast_red;
*plast_red = *pfirst_red;
*pfirst_red = temp;