c - 这两种在 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;
为什么?
解决方案
对于任何指针或数组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
推荐阅读
- r - 2个向量的条件分组/循环
- python - 如何从图像中的对象中去除边缘噪声
- javascript - 如何使用 mongodb MongoClient 发出 GET 请求?
- python - 没有 fit() 的 Tensorboard 使用 keras 和 tf
- apache-spark - 在火花中加入 2 个数据帧后选择特定列
- c++ - C++ - std::unordered_map 中的最坏情况和平均情况插入时间复杂度
? - c# - 为什么我在 Linux/mono 上使用 PCLCypto 得到 DLLnotFoundException
- javascript - docker上的Nginx在刷新时出现404错误?
- f# - 在 F# 序列中需要帮助
- amazon-web-services - Cognito 验证 SAML - 什么是用户名约束?