I don't think memcpy()
is designed for what you want. In general, you would use memcpy()
to copy one or more whole objects (where an object might be an int, a char, a long long, etc.)
int a[4] = { 1, 2, 3, 4 };
int b[3];
int c[5] = { 0 };
::memcpy(b, a, 3 * sizeof(int)); // b is { 1, 2, 3 }
::memcpy(c+2, b, 3 * sizeof(int)); // c is { 0, 0, 1, 2, 3 }
c+2 is not "c + 2 bytes". It is "c + 2 ints" (8 bytes on a Win32/x86 system).
You can access the individual bytes by casting to a char or unsigned char pointer, but I don't recommend that unless you really understand what you're doing as there are many pitfalls.
unsigned x = 0;
unsigned char *px = reinterpret_cast<unsigned char *>(&x);
px[0] = 0xFF;
px[2] = 0xAA;
One of the dangers here is that you are assuming knowledge about how the computer stores an integer. On an x86 system, x will be 0x00AA00FF but on a Sun Sparc system it will be 0xFF00AA00.
if you need to set parts of an integer it is often better to use "or" and "shift".
x = (0xFF<<24) | (0xAA<<8);
will give you 0xFF00AA00 on any architecture.
0xFF<<24 shifts the value 0xFF by 24 bits to the left, making 0xFF000000.
0xAA<<8 shifts the value 0xAA by 8 bits to the left, making 0x0000AA00.
We "or" them together, giving 0xFF00AA00.