Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Copy blocks of memory to another part of memory

Tags:

c++

memory

I'm trying to copy a continuous block of data from one location in the Main Memory to another location. Here's what I did so far, but it's not working. It seems that after applying 'memcpy', the content of my array 'testDump' becomes all zeros.

//Initialize array to store pixel values of a 640x480 image
int testDump[204800];   
for(int k = 0; k<204800; k++)
   testDump[k] = -9;

//pImage is a pointer to the first pixel of an image 
pImage = dmd.Data();

//pTestDump is a pointer to the first element in the array
int* pTestDump = testDump;

//copy content from pImage to pTestDump
memcpy (pTestDump, pImage, 204800);

for(int px_1 = 0; px_1<300; px_1++)
{
   std::cout<<"Add of pPixel: "<<pImage+px_1<<", content: "<<*(pImage+px_1);
   std::cout<<"Add of testDump: "<<pTestDump+px_1<<", content: "<<*(pTestDump+px_1);
}

Advice and suggestions are appreciated.

Thanks

Roronoa Zoro

like image 905
Roronoa Zoro Avatar asked Nov 26 '11 03:11

Roronoa Zoro


People also ask

What is a memory copy?

Description: A copy from the storage specified by source string to the storage specified by target string is performed. Copy length specifies the number of bytes to copy.

Which of the following built in function is used to copy one memory location to another location?

memcpy() function is an inbuilt function in C++ STL, which is defined in <cstring> header file. memcpy() function is used to copy blocks of memory. This function is used to copy the number of values from one memory location to another. The result of the function is a binary copy of the data.

What is memcpy function?

The function memcpy() is used to copy a memory block from one location to another. One is source and another is destination pointed by the pointer. This is declared in “string.

Does memcpy copy byte by byte?

Memcpy copies data bytes by byte from the source array to the destination array. This copying of data is threadsafe.


1 Answers

The first problem I see is this:

memcpy (pTestDump, pImage, 204800);

should be this:

memcpy (pTestDump, pImage, 204800 * sizeof(int));

You forgot the sizeof(int) so you're only copying a part of the data.

The other problem is that you switched the order of the operands in memcpy(). The destination is the first operand:

memcpy (pImage, pTestDump, 204800 * sizeof(int));
like image 90
Mysticial Avatar answered Nov 02 '22 23:11

Mysticial