我使用memcpy错误吗?
在下面的代码片段中,我希望函数接受一个双指针(二维数组),它可以是任何数据类型(在本例中为整数),并使用 memcpy 将数组的一个元素复制到另一个变量。它通过了编译器,但仍然显示访问冲突。
我查遍了论坛的各个地方,但仍然无法解决这个问题。
任何提示表示赞赏。我几乎被 C 的复杂性击垮了。
void ShowImg(void **ptr, IplImage *sample, char window_name[])
{
int value;
IplImage *sml_img= cvCreateImage(cvSize(sample->width,sample->height),IPL_DEPTH_8U, 1);
for(int j=0; j<sample->height; j++)
for(int i=0; i<sample->width; i++){
memcpy(&value, ptr+i*sizeof(int)+j*sample->width*sizeof(int), sizeof(int));
((uchar *)(sml_img->imageData + sml_img->widthStep*j))[i] = value;
printf("%d,%d\n", i, j);
}
cvNamedWindow(window_name);
cvShowImage(window_name, sml_img);
cvWaitKey(0);
cvDestroyWindow(window_name);
cvReleaseImage(&sml_img);
}
in the following snippet I wish the function accept a double pointer(2D array) which can be in any data type(in this case, integer), and use memcpy to copy one element at a time of the array to another variable. It passed the compiler but still shows an access violation.
I looked everywhere around the forum but still can't get this right.
Any tips are appreciated. I am nearly devastated by the complexity of C.
void ShowImg(void **ptr, IplImage *sample, char window_name[])
{
int value;
IplImage *sml_img= cvCreateImage(cvSize(sample->width,sample->height),IPL_DEPTH_8U, 1);
for(int j=0; j<sample->height; j++)
for(int i=0; i<sample->width; i++){
memcpy(&value, ptr+i*sizeof(int)+j*sample->width*sizeof(int), sizeof(int));
((uchar *)(sml_img->imageData + sml_img->widthStep*j))[i] = value;
printf("%d,%d\n", i, j);
}
cvNamedWindow(window_name);
cvShowImage(window_name, sml_img);
cvWaitKey(0);
cvDestroyWindow(window_name);
cvReleaseImage(&sml_img);
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
我认为这里有一个错误:
ptr+i*sizeof(int)
因为ptr
的类型是void**
ptr+1 是下一个element,意思是ptr+sizeof(void*)
,为什么要把它乘以sizeof(int)呢?例如:
我认为这不是你想要的。 (与
j*sample->width*sizeof(int)
相同)I think there's a mistake here:
ptr+i*sizeof(int)
sinceptr
is of typevoid**
ptr+1 is the next element, meaningptr+sizeof(void*)
, why would you multiply it by sizeof(int)?for example:
and I don't think that's what you want. (the same about
j*sample->width*sizeof(int)
)memcpy(3)
实际上用于复制大于基本类型的对象。您可以将此行: 替换为此行:
The
sizeof(int)
scaling is throwing me;如果编译器在编译时知道您的数据类型,那么您不需要这个。为什么你的数组是一个void **
而不是编译器可以使用的更具体的数组? (int **
将是一个很好的开始,但我不太擅长 C 中的多维数组,所以我不确定这会是一个更好的替代品。但我确实不喜欢你的现在有。memcpy(3)
is really for copying objects that are larger than the primitive types. You could replace this line:with this line:
The
sizeof(int)
scaling is throwing me; you shouldn't need this if your datatypes are known to the compiler at compile time. Why is your array avoid **
rather than something more specific, which the compiler could work with? (int **
would be a good first start, but I'm not very good at multidimensional arrays in C, so I'm not positive this would be a better replacement. But I do dislike what you have now. :)