Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Memcpy : Adding an int offset?

Tags:

c++

c

memcpy

I was looking over some C++ code and I ran into this memcpy function. I understand what memcpy does but they add an int to the source. I tried looking up the source code for memcpy but I can't seem to understand what the adding is actually doing to the memcpy function.

memcpy(Destination, SourceData + intSize, SourceDataSize);

In other words, I want to know what SourceData + intSize is doing. (I am trying to convert this to java.)

EDIT:

So here is my attempt at doing a memcpy function in java using a for loop...

for(int i = 0 ; i < SourceDataSize ; i ++ ) {
      Destination[i] = SourceData[i + 0x100];
}
like image 420
user1007682 Avatar asked Dec 04 '22 17:12

user1007682


2 Answers

It is the same thing as:

memcpy(&Destination[0], &SourceData[intSize], SourceDataSize);
like image 184
ronag Avatar answered Dec 21 '22 04:12

ronag


This is basic pointer arithmetic. SourceData points to some data type, and adding n to it increases the address it's pointing to by n * sizeof(*SourceData).

For example, if SourceData is defined as:

uint32_t *SourceData;

and

sizeof(uint32_t) == 4

then adding 2 to SourceData would increase the address it holds by 8.

As an aside, if SourceData is defined as an array, then adding n to it is sometimes the same as accessing the nth element of the array. It's easy enough to see for n==0; when n==1, it's easy to see that you'll be accessing a memory address that's sizeof(*SourceData) bytes after the beginning of the array.

like image 25
Ori Pessach Avatar answered Dec 21 '22 05:12

Ori Pessach