下面的代码在下面显示的测试中显然将2d数据从src复制到dst,而没有“问题”,但是我知道代码是错误的,并且还提供了正确的代码。在这里,我在问什么是完全错误的。我的解释是指针本身是一个多字节变量,如果指针值(无符号字符)的大小与指针的大小不同,则取消引用双指针会遇到麻烦。你怎么看?
我必须指出,强制类型转换“ unsigned char **”不会更改基础数据,因此,如果将代码修改为使用另一个本地间接寻址,则所有内容实际上都可以正常运行,请参见下文:
void copy_2d_data(unsigned char **dst, unsigned char **src, int w, int h)
{
printf("copy_2d_data img width = %d, height = %d\n ......\n", w, h);
// wrong code:
for (int row=0; row<w-2; row++) { //note here -> w-2
for (int col=0; col<h-2; col++) { //note here -> h-2
//**dst++ = **src++; //this will cause seg fault, so don't try it
*dst++ = *src++;
}
}
#if 0 // the correct code starts:
unsigned char *s = (unsigned char *)src;
unsigned char *d = (unsigned char *)dst;
for (int row=0; row<w; row++) {
for (int col=0; col<h; col++) {
*d++ = *s++;
}
}
#endif
printf("copy_2d_data done\n");
}
测试:
#include <stdio.h>
int main()
{
unsigned char s_img[][5] = {{1, 2, 3, 4, 5 },
{6, 7, 8, 9, 10},
{11, 12, 13, 14, 15},
{16, 17, 18, 19, 20},
{21, 22, 23, 24, 25}
};
unsigned char d_img[][5] = {{0, 0, 0, 0, 0},
{0, 0, 0, 0, 0},
{0, 0, 0, 0, 0},
{0, 0, 0, 0, 0},
{0, 0, 0, 0, 0}
};
int w = 5, h = 5;
//display what is in img buf:
unsigned char *s = (unsigned char *)s_img;
unsigned char *d = (unsigned char *)d_img;
printf("\ns_img:\n");
for (int row =0; row<w; row++) {
for (int col =0; col<h; col++) {
printf("%u,", *s++);
}
printf("\n");
}
printf("\nd_img:\n");
for (int row =0; row<w; row++) {
for (int col =0; col<h; col++) {
printf("%u,", *d++);
}
printf("\n");
}
printf("\n");
//copy:
copy_2d_data( (unsigned char **)d_img, (unsigned char **)s_img, w, h );
printf("\nnow check result\nd_img:\n");
d = (unsigned char *)d_img;
for (int row=0; row<w; row++) {
for (int col =0; col<h; col++) {
printf("%u,", *d++);
}
printf("\n");
}
return 0;
}
输出:
s_img:
1,2,3,4,5,
6,7,8,9,10,
11,12,13,14,15,
16,17,18,19,20,
21,22,23,24,25,
d_img:
0,0,0,0,0,
0,0,0,0,0,
0,0,0,0,0,
0,0,0,0,0,
0,0,0,0,0,
copy_2d_data img width = 5, height = 5
......
copy_2d_data done
now check result
d_img:
1,2,3,4,5,
6,7,8,9,10,
11,12,13,14,15,
16,17,18,19,20,
21,22,23,24,25,
最佳答案
它不起作用,或者运气不好(暂时)。
点对点指针与2D数组无关,也不能指向2D数组。在处理指针数组时,可以使用指针到指针,但是这里不是这种情况。这就是为什么您不能在copy_2d_data
调用期间不添加不正确的强制转换的情况下编译此代码的原因。
您可以将函数更改为此:
void copy_2d_data (int row, int col, unsigned char dst[row][col], unsigned char src[row][col])
{
printf("copy_2d_data img width = %d, height = %d\n ......\n", w, h);
for (int r=0; r<row-2; r++) {
for (int c=0; c<col-2; c++) {
dst[row][col]
}
}
printf("copy_2d_data done\n");
}
(也请不要一时称呼高度+宽度,一时再称呼+ col,这就是疯狂之路。)
然后将函数调用为:
copy_2d_data(w, h, d_img, s_img);