[英]What's the difference between these two ways of incrementing pointers for a 2D array in C?
我對 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;
為什么?
對於任何指針或數組p
和索引i
,表達式*(p + i)
完全等於p[i]
。
這意味着您的第二個循環確實可以
int i;
for (i = 0; i < (height * width); i++)
{
rgb[i] = copy[i];
}
我相信上面的版本更清楚地說明了正在發生的事情以及它為什么起作用。
第一個循環的問題是你修改了rgb
和copy
,所以你失去了原始指針。 您需要使用臨時指針才能使其工作:
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
在第一個代碼中,當您到達此處時:
free(copy);
copy
已被修改,因此嘗試free
它是無效的。 您需要釋放malloc
返回的原始指針。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.