Anthony
Anthony

Reputation: 51

Did I use memcpy wrong?

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);

}

Upvotes: 0

Views: 1368

Answers (2)

MByD
MByD

Reputation: 137432

I think there's a mistake here: ptr+i*sizeof(int) since ptr is of type void** ptr+1 is the next element, meaning ptr+sizeof(void*), why would you multiply it by sizeof(int)?

for example:

ptr = 0x00000000, 
sizeof(void*) = 4, 
sizeof(int) = 4
||
\/
ptr+1 = 0x00000004. 
ptr+1*sizeof(int) = 0x00000010.

and I don't think that's what you want. (the same about j*sample->width*sizeof(int))

Upvotes: 3

sarnold
sarnold

Reputation: 104100

memcpy(3) is really for copying objects that are larger than the primitive types. You could replace this line:

memcpy(&value, ptr+i*sizeof(int)+j*sample->width*sizeof(int), sizeof(int));

with this line:

value = ptr+i*sizeof(int)+j*sample->width*sizeof(int);

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 a void ** 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. :)

Upvotes: 1

Related Questions