首页 > 解决方案 > 这两种在 C 中为 2D 数组递增指针的方法有什么区别?

问题描述

我对C很陌生,这是我在这里的第一个问题,所以我希望我能清楚我的问题。

我编写了一个将过滤器应用于 .bmp 图像的函数。在函数内部,我通过malloc()分配内存以存储具有新值的每个像素。完成后,我想通过指针将新值分配给原始像素。我尝试了两种方法,一种有效,另一种无效,但我不明白其中的区别。

这里我声明了两个指针:

RGBTRIPLE *copy = malloc(height * width * sizeof(RGBTRIPLE)); //RGBTRIPLE is the pixel struct
if (copy == NULL)
{
    fprintf(stderr, "Memory allocation error\n");
    exit(2);
}
RGBTRIPLE *rgb = &image[0][0]; // this points to first element of original image

这是我尝试分配新值的两种方法。以下不起作用:

int i;
for (i = 0; i < (height * width); i++)
{
    *rgb = *copy;
    rgb++;
    copy++;     
}
free(copy);
return;

这个确实有效:

int i;
for (i = 0; i < (height * width); i++)
{
    *((RGBTRIPLE *)rgb + i) = *((RGBTRIPLE *)copy + i);
}
free(copy);
return;

为什么?

标签: carrayspointersmultidimensional-array

解决方案


对于任何指针或数组p和索引i表达式*(p + i)完全等于。p[i]

这意味着您的第二个循环确实可以

int i;
for (i = 0; i < (height * width); i++)
{
    rgb[i] = copy[i];
}

我相信上面的版本更清楚地说明了正在发生的事情以及它为什么起作用。


第一个循环的问题是你修改rgbcopy,所以你失去了原来的指针。您需要使用临时指针才能使其工作:

int i;
RGBTRIPLE *temp_rgb = rgb;
RGBTRIPLE *temp_copy = copy;
for (i = 0; i < (height * width); i++)
{
    *temp_rgb = *temp_copy;
    temp_rgb++;
    temp_copy++;     
}

// Here the original values of rgb and copy still exists

推荐阅读